首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

WCF 技術深度剖析(五):ASP.NET 相容模式打造支援 Session 的 WCF 服務

     編輯:關於.NET

前言:打破 WCF 無狀態限制

預設 IIS 寄宿採用「ASP.NET 並行模式」,WCF 管道在 PostAuthenticateRequest 即攔截請求,HttpContext.Current 永遠為 null,無法使用 ASP.NET Session。啟用 ASP.NET 相容模式,讓 .svc 請求完整走完 ASP.NET 管道(由 HttpHandler 處理),即可借用 HttpContext.Session 實現有狀態服務。

一、兩種 IIS 寄宿模式對比

特性並行模式 (預設)相容模式
處理管道HttpModule (PostAuthenticateRequest 截斷)HttpHandler (完整生命週期)
HttpContextnull可用
Session 支援不可用可用
URL 授權失效生效
身分模擬失效生效

二、啟用相容模式三步驟

  1. 服務類別標註 [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
  2. 配置檔 <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
  3. 綁定啟用 Cookie 傳遞:<wsHttpBinding> <binding allowCookies="true" /> </wsHttpBinding>

三、實戰:累積計算服務

1. 契約:以會話狀態保留運算結果

[ServiceContract]
public interface ICalculator
{
    [OperationContract] void Add(double x);
    [OperationContract] void Subtract(double x);
    [OperationContract] void Multiply(double x);
    [OperationContract] void Divide(double x);
    [OperationContract] double GetResult();
}

2. 服務實作:讀寫 HttpContext.Session

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class CalculatorService : ICalculator
{
    private const string Key = "__Result";
    private double CurrentResult
    {
        get => HttpContext.Current.Session[Key] as double? ?? 0;
        set => HttpContext.Current.Session[Key] = value;
    }
    public void Add(double x) => CurrentResult += x;
    public void Subtract(double x) => CurrentResult -= x;
    public void Multiply(double x) => CurrentResult *= x;
    public void Divide(double x) => CurrentResult /= x;
    public double GetResult() => CurrentResult;
}

3. 客戶端配置啟用 Cookie

<endpoint address="..." binding="wsHttpBinding" 
          bindingConfiguration="CookieBinding" contract="ICalculator" />
<bindings>
  <wsHttpBinding>
    <binding name="CookieBinding" allowCookies="true" />
  </wsHttpBinding>
</bindings>

原理:ASP.NET Session 依賴 Cookie 傳遞 SessionId。WCF 預設不傳送/接收 Cookie,設定 allowCookies="true" 後,客戶端自動攜帶並儲存伺服器回傳的 Cookie,維持會話關聯。

四、執行結果

初始值:0
Add(3) → 3
Multiply(10) → 30
Subtract(2) → 28

完美展示跨呼叫保留狀態。

總結

ASP.NET 相容模式 + allowCookies 讓 WCF 在 IIS 中輕鬆獲得 Session 能力,適合移植既有 ASP.NET 應用、需共享 Session 的混合架構。但需注意:此模式綁定 HTTP/IIS,失去 WCF 多傳輸協定的優勢。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved