1

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?

infused
  • 24,000
  • 13
  • 68
  • 78
Akhil
  • 1,918
  • 5
  • 30
  • 74

2 Answers2

1

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;
            }
        }
    }
ajaysinghdav10d
  • 1,771
  • 3
  • 23
  • 33
0

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

Aiden Strydom
  • 1,198
  • 2
  • 14
  • 43