首页 > 其他 > 详细

关于WCF SessionId的说明

时间:2015-07-14 11:15:23      阅读:297      评论:0      收藏:0      [点我收藏+]

    在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

 

关于WCF SessionId的说明

原文:http://www.cnblogs.com/huatao/p/4644874.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!