Akhil
Akhil

Reputation: 2030

Session Variable in WCF Service

I am just creating a normal wcf service which get the Person object and returns the List. I need to save incoming Person object in a session and returns the list. I have implemented the code like below

[AspNetCompatibilityRequirements(RequirementsMode= AspNetCompatibilityRequirementsMode.Required)]
public class Service1 : IService1
{
    public List<Person> getPerson(Person person)
    {
        List<Person> persons;
        if (HttpContext.Current.Session["personList"] != null)
        {
            persons = (List<Person>)HttpContext.Current.Session["personList"];
        }
        else
        {
            persons = new List<Person>();
        }
        persons.Add(person);
        HttpContext.Current.Session["personList"] = persons;

        return persons;
    }
}

But always i got only the object i passed in the parameter. Not the entire collection. So always session is returns null. What i missed?

Upvotes: 1

Views: 5070

Answers (2)

Aiden Strydom
Aiden Strydom

Reputation: 1208

Your Service contract needs the following adornment

ServiceContract(SessionMode=SessionMode.Required)   

however, do note that you can only maintain session state over a secured binding such as wsHttpBinding

Upvotes: 0

ajaysinghdav10d
ajaysinghdav10d

Reputation: 1957

The scope of the current session gets over immediately after the response is returned. You need to create a session manager class. Please see the working code below:-

    [AspNetCompatibilityRequirements(RequirementsMode= AspNetCompatibilityRequirementsMode.Required)]
    public class Service1 : IService1
    {
        public List<Person> getPerson(Person person)
        {
            SessionManager.PersonCollectionSetter = person;
            return SessionManager.PersonCollectionGetter;
        }
    }
    public static class SessionManager
    {
        private static List<Person> m_PersonCollection = new List<Person>();
        public static Person PersonCollectionSetter
        {
            set
            {
                m_PersonCollection.Add(value);
            }
        }

        public static List<Person> PersonCollectionGetter
        {
            get
            {
                return m_PersonCollection;
            }
        }
    }

Upvotes: 1

Related Questions