介紹
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