萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET Generic Handler (ASHX) 中存取 Session 的正確姿勢:實作 IReadOnlySessionState / IRequiresSessionState

核心問題

預設 `IHttpHandler` **不支援 Session**。直接呼叫 `context.Session["Key"]` 會拋出 `NullReferenceException` ("物件參考未設定為物件的執行個體"),因為 `HttpContext.Session` 為 `null`。

解決方案:實作標記介面

介面命名空間權限適用場景
IReadOnlySessionState System.Web.SessionState **唯讀** 僅需讀取 Session (如驗證身分、取得使用者資訊)
IRequiresSessionState System.Web.SessionState **讀寫** 需修改 Session (如購物車、暫存表單資料)

兩者皆為**標記介面** (Marker Interface),無任何成員,僅通知 ASP.NET 管線為此 Handler 啟用 Session 模組。

完整實作範例

using System;
using System.Web;
using System.Web.SessionState;

namespace DtlCalendar.Mobile.Site.Manage
{
    /// 
    /// 刪除 APK 檔案處理程式 (唯讀 Session 驗證登入用戶)
    /// 
    public class DelApk : IHttpHandler, IReadOnlySessionState
    {
        public void ProcessRequest(HttpContext context)
        {
            // 1. 取得請求參數
            string strId = context.Request["id"];
            
            // 2. 設定回應格式
            context.Response.Clear();
            context.Response.ContentType = "text/plain";

            // 3. 驗證參數與登入狀態
            if (int.TryParse(strId, out int id) && IsLoggedIn(context, out string userAccount))
            {
                // 4. 執行業務邏輯
                string result = DataProvider.MobileDataProvider.CreateInstance().DelMApk(id).ToString();
                
                // 5. 記錄操作日誌
                BLL.LogOprHelper.Instance.InsertMLog(userAccount, BLL.LogOpr.Delete, $"DelApk result:{result}");
                
                context.Response.Write(result);
            }
            else
            {
                BLL.LogOprHelper.Instance.InsertMLog(strId, BLL.LogOpr.Delete, "DelApk result:-1");
                context.Response.Write("-1");
            }
        }

        /// 
        /// 從 Session 取得登入用戶
        /// 
        private bool IsLoggedIn(HttpContext context, out string userAccount)
        {
            userAccount = string.Empty;
            
            if (context.Session["LoginUser"] != null)
            {
                var user = context.Session["LoginUser"] as BLL.User;
                if (user != null)
                {
                    userAccount = user.Account;
                    return true;
                }
            }
            return false;
        }

        public bool IsReusable => true; // 無狀態可重用
    }
}

原理深度解析

  1. ASP.NET 管線在 `PostAcquireRequestState` 階段檢查 Handler 是否實作 `IRequiresSessionState` 或 `IReadOnlySessionState`。
  2. 若實作,`SessionStateModule` 會從 Session State Provider (InProc/StateServer/SQL Server/Custom) 載入 Session 資料並指派給 `HttpContext.Session`。
  3. `IReadOnlySessionState` 會在 `ReleaseRequestState` 時**略過寫入/鎖定釋放**,效能略優於 `IRequiresSessionState`。

常見錯誤與避坑

  • ❌ **忘記引用命名空間** `using System.Web.SessionState;` → 介面找不到。
  • ❌ **同時實作兩個介面** → 編譯通過但語意混淆,按需選擇其一。
  • ❌ **在 `IsReusable = true` 且使用 `IRequiresSessionState` 時存放實例欄位** → 跨請求共用實例會導致 Session 資料洩漏/競爭。**Handler 應為無狀態**,所有狀態放在 `context.Session` / `context.Items` / 資料庫。
  • ❌ **Session 狀態模式為 StateServer/SQL Server 時,自訂類別未標記 `[Serializable]`** → 序列化失敗。

ASHX vs ASPX vs Web API / MVC Controller

特性ASHX (Generic Handler)ASPX (Web Form)Web API / MVC Controller
生命週期極輕量 (無頁面事件)完整頁面生命週期Controller/Action 管線
Session 支援需實作標記介面內建支援內建支援
適用場景圖片輸出、檔案下載、AJAX 端點、RSS、Sitemap、動態 JS/CSS傳統表單頁面REST API、現代 Web 應用
效能最高較低 (ViewState、Control Tree)高 (無 ViewState)

現代化建議

  • 新專案優先使用 **ASP.NET Core Minimal APIs** 或 **Controller**,內建 Dependency Injection、模型繫結、驗證、OpenAPI 整合。
  • 既有 ASHX 遷移:提取業務邏輯至 Service 層,Controller/Minimal API 僅負責 HTTP 協定處理。
  • 若必須維護 ASHX,請嚴格遵守「實作正確 Session 介面 + 無狀態 Handler + 業務邏輯外移」原則。

總結

ASHX 存取 Session 的關鍵在於**實作 `IReadOnlySessionState` (唯讀) 或 `IRequiresSessionState` (讀寫)**。這是 ASP.NET 管線機制的硬性要求,理解其背後的 `SessionStateModule` 運作時機,能避免常見的 `NullReferenceException` 並正確選擇讀寫模式以優化效能。

copyright © 萬盛學電腦網 all rights reserved