简体   繁体   English

WCF服务中的会话变量

[英]Session Variable in WCF Service

I am just creating a normal wcf service which get the Person object and returns the List. 我只是在创建一个普通的wcf服务,该服务获取Person对象并返回List。 I need to save incoming Person object in a session and returns the list. 我需要在会话中保存传入的Person对象并返回列表。 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. 因此,会话总是返回null。 What i missed? 我错过了什么?

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;
            }
        }
    }

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 但是,请注意,您只能在诸如wsHttpBinding类的安全binding维护会话状态

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM