化零为整WCF(11) - 会话状态(Session)

简介:
[索引页]
[源码下载] 


化零为整WCF(11) - 会话状态(Session)


作者: webabcd


介绍
WCF(Windows Communication Foundation) - 会话状态:
    ServiceContract
    ·
SessionMode.Allowed - 指定当传入绑定支持会话时,协定也支持会话(默认值)
    · SessionMode.Required -  指定协定需要会话绑定。如果绑定并未配置为支持会话,则将引发异常
    · SessionMode.NotAllowed - 指定协定永不支持启动会话的绑定
    OperationContract
    ·
IsInitiating - 获取或设置一个值,该值指示方法是否实现可在服务器上启动会话(如果存在会话)的操作。
    ·IsTerminating - 获取或设置一个值,该值指示服务操作在发送答复消息(如果存在)后,是否会导致服务器关闭会话。


示例
1、服务
IHello.cs
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
 
using System.ServiceModel; 
 
namespace WCF.ServiceLib.SessionManagement 

         /// <summary> 
         /// 演示会话状态的接口 
         /// </summary>NotAllowed 
         /// <remarks> 
        /// SessionMode - 获取或设置是否允许、不允许或要求会话 
        /// SessionMode.Allowed - 指定当传入绑定支持会话时,协定也支持会话(默认值) 
        /// SessionMode.Required -    指定协定需要会话绑定。如果绑定并未配置为支持会话,则将引发异常 
        /// SessionMode.NotAllowed - 指定协定永不支持启动会话的绑定 
        /// </remarks> 

        [ServiceContract(SessionMode = SessionMode.Required)] 
         public  interface IHello 
        { 
                 /// <summary> 
                 /// 初始化Session 
                 /// </summary> 
                 /// <remarks> 
                /// IsInitiating - 获取或设置一个值,该值指示方法是否实现可在服务器上启动会话(如果存在会话)的操作。 
                /// IsTerminating - 获取或设置一个值,该值指示服务操作在发送答复消息(如果存在)后,是否会导致服务器关闭会话。 
                /// </remarks> 

                [OperationContract(IsInitiating =  true, IsTerminating =  false)] 
                 void StartSession(); 
 
                 /// <summary> 
                 /// 结束Session 
                 /// </summary> 
                [OperationContract(IsInitiating =  false, IsTerminating =  true)] 
                 void StopSession(); 
 
                 /// <summary> 
                 /// 获取计数器结果 
                 /// </summary> 
                 /// <returns></returns> 
                [OperationContract(IsInitiating =  false, IsTerminating =  false)] 
                 int Counter(); 
 
                 /// <summary> 
                 /// 获取SessionId 
                 /// </summary> 
                 /// <returns></returns> 
                [OperationContract(IsInitiating =  false, IsTerminating =  false)] 
                 string GetSessionId(); 
        } 
}
 
Hello.cs
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
 
using System.ServiceModel; 
 
namespace WCF.ServiceLib.SessionManagement 

         /// <summary> 
         /// 演示会话状态的接口 
         /// </summary> 
         /// <remarks> 
        /// InstanceContextMode - 获取或设置指示新服务对象何时创建的值。 
        /// InstanceContextMode.PerSession - 为每个会话创建一个新的 System.ServiceModel.InstanceContext 对象。 
        /// InstanceContextMode 的默认值为 InstanceContextMode.PerSession 
        /// </remarks> 

        [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)] 
         public  class Hello : IHello 
        { 
                 private  int _counter; 
 
                 /// <summary> 
                 /// 初始化Session 
                 /// </summary> 
                 public  void StartSession() 
                { 
                        _counter = 0; 
                } 
 
                 /// <summary> 
                 /// 结束Session 
                 /// </summary> 
                 public  void StopSession() 
                { 
                        _counter = 0; 
                } 
 
                 /// <summary> 
                 /// 获取计数器结果 
                 /// </summary> 
                 /// <returns></returns> 
                 public  int Counter() 
                { 
                        _counter++; 
 
                         return _counter; 
                } 
 
                 /// <summary> 
                 /// 获取SessionId 
                 /// </summary> 
                 /// <returns></returns> 
                 public  string GetSessionId() 
                { 
                         return OperationContext.Current.SessionId; 
                } 
        } 
}
 
 
2、宿主
Hello.svc
<%@ ServiceHost Language="C#" Debug="true" Service="WCF.ServiceLib.SessionManagement.Hello" %>
 
Web.config
<?xml version="1.0"?> 
<configuration> 
        <system.serviceModel> 
                <behaviors> 
                        <serviceBehaviors> 
                                <behavior name="SessionManagementBehavior"> 
                                        <!--httpGetEnabled - 使用get方式提供服务--> 
                                        <serviceMetadata httpGetEnabled="true" /> 
                                        <serviceDebug includeExceptionDetailInFaults="true"/> 
                                </behavior> 
                        </serviceBehaviors> 
                </behaviors> 
                <services> 
                        <!--name - 提供服务的类名--> 
                        <!--behaviorConfiguration - 指定相关的行为配置--> 
                        <service name="WCF.ServiceLib.SessionManagement.Hello" behaviorConfiguration="SessionManagementBehavior"> 
                                <!--address - 服务地址--> 
                                <!--binding - 通信方式--> 
                                <!--contract - 服务契约--> 
                                <!--bindingConfiguration - 指定相关的绑定配置--> 
                                <endpoint address="" binding="wsHttpBinding" contract="WCF.ServiceLib.SessionManagement.IHello" bindingConfiguration="SessionManagementBindingConfiguration"/> 
                        </service> 
                </services> 
                <bindings> 
                        <wsHttpBinding> 
                                <!--wsHttpBinding 可提供 安全会话 和 可靠会话--> 
                                <!--receiveTimeout - 在传输引发异常之前可用于完成读取操作的时间间隔(此处可认为是Session过期时间)--> 
                                <binding name="SessionManagementBindingConfiguration" receiveTimeout="00:00:10"> 
                                        <!--指示是否在通道终结点之间建立 WS-RM (WS-ReliableMessaging) 可靠会话。默认值为 false。--> 
                                        <reliableSession enabled="true"/> 
                                        <security> 
                                                <!--此属性控制安全上下文令牌是否通过客户端与服务之间的 WS-SecureConversation 交换建立。将它设置为 true 要求远程方支持 WS-SecureConversation。--> 
                                                <message establishSecurityContext="true"/> 
                                        </security> 
                                </binding> 
                        </wsHttpBinding> 
                </bindings> 
        </system.serviceModel> 
</configuration>
 

3、客户端
Hello.aspx
<%@ Page Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Hello.aspx.cs" 
        Inherits="InstanceMode_Hello" Title="会话状态(Session)" %> 

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server"> 
</asp:Content> 
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server"> 
        <asp:Button ID="btnStartSession" runat="server" Text="StartSession" OnClick="btnStartSession_Click" /> 
          
        <asp:Button ID="btnCounter" runat="server" Text="Counter" OnClick="btnCounter_Click" /> 
          
        <asp:Button ID="btnGetSessionId" runat="server" Text="GetSessionId" OnClick="btnGetSessionId_Click" /> 
          
        <asp:Button ID="btnStopSession" runat="server" Text="StopSession" OnClick="btnStopSession_Click" /> 
</asp:Content>
 
Hello.aspx.cs
using System; 
using System.Collections; 
using System.Configuration; 
using System.Data; 
using System.Linq; 
using System.Web; 
using System.Web.Security; 
using System.Web.UI; 
using System.Web.UI.HtmlControls; 
using System.Web.UI.WebControls; 
using System.Web.UI.WebControls.WebParts; 
using System.Xml.Linq; 
 
public partial  class InstanceMode_Hello : System.Web.UI.Page 

        SessionManagemenSvc.HelloClient _proxy =  null
 
         protected  void Page_Load( object sender, EventArgs e) 
        { 
                 if (Session[ "proxy"] ==  null
                        Session[ "proxy"] =  new SessionManagemenSvc.HelloClient(); 
 
                _proxy = Session[ "proxy"as SessionManagemenSvc.HelloClient; 
        } 
 
         protected  void btnStartSession_Click( object sender, EventArgs e) 
        { 
                _proxy.StartSession(); 
        } 
 
         protected  void btnCounter_Click( object sender, EventArgs e) 
        { 
                Page.ClientScript.RegisterStartupScript( 
                         this.GetType(), 
                         "js"
                         string.Format( "alert('计数器:{0}')", _proxy.Counter()), 
                         true); 
        } 
 
         protected  void btnGetSessionId_Click( object sender, EventArgs e) 
        { 
                Page.ClientScript.RegisterStartupScript( 
                      this.GetType(), 
                      "js"
                      string.Format( "alert('SessionId:{0}')", _proxy.GetSessionId()), 
                      true); 
        } 
 
         protected  void btnStopSession_Click( object sender, EventArgs e) 
        { 
                _proxy.StopSession(); 
        } 
}
 
Web.config
<?xml version="1.0"?> 
<configuration> 
        <system.serviceModel> 
                <client> 
                        <!--address - 服务地址--> 
                        <!--binding - 通信方式--> 
                        <!--contract - 服务契约--> 
                        <!--bindingConfiguration - 指定相关的绑定配置--> 
                        <endpoint address="http://localhost:3502/ServiceHost/SessionManagement/Hello.svc" binding="wsHttpBinding" contract="SessionManagemenSvc.IHello" bindingConfiguration="SessionManagementBindingConfiguration" /> 
                </client> 
                <bindings> 
                        <wsHttpBinding> 
                                <binding name="SessionManagementBindingConfiguration"> 
                                        <!--指示是否在通道终结点之间建立 WS-RM (WS-ReliableMessaging) 可靠会话。默认值为 false。--> 
                                        <reliableSession enabled="true"/> 
                                        <security> 
                                                <!--此属性控制安全上下文令牌是否通过客户端与服务之间的 WS-SecureConversation 交换建立。将它设置为 true 要求远程方支持 WS-SecureConversation。--> 
                                                <message establishSecurityContext="true"/> 
                                        </security> 
                                </binding> 
                        </wsHttpBinding> 
                </bindings> 
        </system.serviceModel> 
</configuration>
 
 

运行结果:
单击" btnStartSession"按钮,初始化Session
单击" btnCounter"按钮,Session级别的计数器累加
单击" btnGetSessionId"按钮,获取当前Session的SessionId
单击" btnStopSession"按钮,终止Session

注:
Host中的 wsHttpBinding配置的 receiveTimeout属性为Session的过期时间


OK
[源码下载]

     本文转自webabcd 51CTO博客,原文链接:http://blog.51cto.com/webabcd/344151 ,如需转载请自行联系原作者



相关文章
|
.NET 开发框架 数据安全/隐私保护