預設 `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; // 無狀態可重用
}
}
| 特性 | 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) |
ASHX 存取 Session 的關鍵在於**實作 `IReadOnlySessionState` (唯讀) 或 `IRequiresSessionState` (讀寫)**。這是 ASP.NET 管線機制的硬性要求,理解其背後的 `SessionStateModule` 運作時機,能避免常見的 `NullReferenceException` 並正確選擇讀寫模式以優化效能。