关于WCF SessionId的说明

    在WCF中,会话(Session)是服务端获取客户端会话信息的一种机制,本文描述了会话存在的前提条件和范围,以及具体操作。

    一、会话前提条件

    WCF中存在会话的前提条件有:

    1、契约属性SessionMode

    契约协定中的SessionMode必须为Allowed(默认)或Required,代码示例如下:

using System.ServiceModel;

namespace SessionIdTest
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IHello" in both code and config file together.
    [ServiceContract(SessionMode = SessionMode.Required)]
    public interface IHello
    {
        [OperationContract]
        void Login(string name);

        [OperationContract]
        string Say(string content);

        [OperationContract]
        void Test();
    }
}
View Code

    2、服务绑定

    服务绑定必须能支持会话。

    注意,BasicHttpBinding、MSMQ相关绑定是不支持会话的。

    二、客户端如何传递SessionId到服务端

    1、客户端代码

    在客户端创建一个服务代理实例,将其放到OperationContextScope实例中使用。

    另外,服务代理实例必须先Open,或先调用一个服务方法,才能使用SessionId。

    使用SessionId的方法是:OperationContext.Current.SessionId。

    代码如下:

            var client = new ss.HelloClient();
            string sessionId = string.Empty;
            using (OperationContextScope sp = new OperationContextScope(client.InnerChannel))
            {
                client.Open();
                client.Test();
                sessionId = OperationContext.Current.SessionId;
            }
View Code

    2、服务端代码

    服务端访问客户端会话ID的方法与客户端一样:OperationContext.Current.SessionId。

    代码如下:

        public string Say(string content)
        {
            string str = OperationContext.Current.SessionId;
            return str;
        }
View Code
原文地址:https://www.cnblogs.com/huatao/p/4644874.html