天天看點

WCF 及 Silverlight 中使用 Session

WCF 中 使用 Session

1.标記WCF服務開啟Session模式,使用SessionMode 來使Session有效化

[ServiceContract(SessionMode = SessionMode.Required)]

2.服務類添加ASPNETSESSION相容标記

[System.ServiceModel.Activation.AspNetCompatibilityRequirements(RequirementsMode = System.ServiceModel.Activation.AspNetCompatibilityRequirementsMode.Required)]

using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Collections.Generic;
using System.Text;



namespace Service
{
    [ServiceContract(SessionMode = SessionMode.Required)]
    [AspNetCompatibilityRequirements(RequirementsMode = System.ServiceModel.Activation.AspNetCompatibilityRequirementsMode.Required)]  
    public partial class Service
    {
    }
}
      

3.配置WEB.CONFIG檔案中<system.serviceModel>節

    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"></serviceHostingEnvironment>

<!--WCF Siverlight 配置-->
<system.serviceModel>
    
    <behaviors>
        <serviceBehaviors>
            <behavior name=".Service.ServiceBehavior">
                <serviceMetadata httpGetEnabled="true" />
                <serviceDebug includeExceptionDetailInFaults="false" />
            </behavior>
        </serviceBehaviors>
    </behaviors>
    <bindings>
        <customBinding>
            <binding name="customBinding0">
                <binaryMessageEncoding />
                <httpTransport>
                    <extendedProtectionPolicy policyEnforcement="Never" />
                </httpTransport>
            </binding>
        </customBinding>
    </bindings>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />  <!--這裡配置-->
    <services>
        <service behaviorConfiguration=".Service.ServiceBehavior" name=".Service.Service">
            <endpoint address="" binding="customBinding" bindingConfiguration="customBinding0" contract=".Service.Service" />
            <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
        </service>
    </services>
</system.serviceModel>      

網絡資源:

WCF狀态儲存分為兩步:

(1) 使用SessionMode 來使Session有效化

  1. [ServiceContract(SessionMode

    SessionMode=SessionMode.Required)]  

  2. public interface ICalculator  
  3. {  
  4. [OperationContract(IsOneWay=true)]  
  5. void Adds(double x);  
  6. [OperationContract]  
  7. double GetResult();  
  8. }

(2)ServiceBehavior 裡面利用參數InstanceContextMode設定到底使用哪一種Session方式

  1. [ServiceBehavior(InstanceContextMode

    InstanceContextMode=InstanceContextMode.PerCall)]  

  2. public class CalculatorService:ICalculator  
  3. {  }

WCF狀态儲存SessionMode 有三種值:

(1)Allowed 預設選值,允許但不強制使用Session

(2)Required 強制使用Session

(3)NotAllowed 不允許使用Session

WCF狀态儲存InstanceContextMode 有三種值:

(1) Percall 為user的每一次調用生成一個SessionID

生命周期:調用開始 ---->調用結束,這種情況和不使用Session是一樣的

(2) PerSession 為每個使用者生成一個SessionID

生命周期:用戶端代理生成--->用戶端代理關閉 和最原先的Session是一樣的

(3) Seigle 生成唯一的SessionID,所有的使用者共享 從host建立---->host 關閉,和Application 一樣

在Silverlight中使用SESSION

首先Session是運作在伺服器上的,而Silverlight運作在用戶端。是以在Silverlight中使用SESSION的說法并不準确,

隻因大家經常這樣搜尋才起這個名字。

有兩種方法實作Silverlight與Session的關聯:

方法一、通過WCF使用ASP.NET中的Session[因BasicHttpBinding不支援WCF中的Session,如使用WCF會話将報錯 ]

  首先:在web.config中<system.serviceModel >下添加:

    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>

  然後:在服務類[不是接口]下添加如下屬性:

    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

  接下來就可以使用Session記得添加System.Web的引用

    HttpContext.Current.Session["YourName"] = something;

    object something = HttpContext.Current.Session["YourName"];

方法二、在用戶端建立一個靜态類模拟Session

  如要儲存登陸資訊,可在驗證了使用者名、密碼之後在用戶端儲存相關資訊。

using System;

using System.Collections.Generic;

namespace SessionDemo

{

public static class SessionManager

    {

private static Dictionary<string, object> session = new Dictionary<string, object>();

public static Dictionary<string, object> Session

        {

get { return SessionManager.session; }

set { SessionManager.session = value; }

        }

    }

}

使用方法:

指派:

SessionManager.Session["uname"] = "kunal";

取值:

txbUname.Text = SessionManager.Session["uname"].ToString();

介紹
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的過期時間       
以上内容出自網絡,并非原創      

繼續閱讀