預設 `<%@ WebHandler %>` 產生的類別僅實作 `IHttpHandler`,不支援 Session。直接呼叫 `context.Session` 會拋出 `NullReferenceException`。
using System;
using System.Web;
using System.Web.SessionState;
namespace MyApp.Handlers
{
///
/// 需要「讀寫」 Session 時實作 IRequiresSessionState
/// 僅需「讀取」 Session 時實作 IReadOnlySessionState(效能略佳)
///
public class SecureHandler : IHttpHandler, IRequiresSessionState
{
public bool IsReusable => false; // 若有共用狀態請設 false
public void ProcessRequest(HttpContext context)
{
// 1. 取得 Session 物件(已由 ASP.NET 自動載入)
var session = context.Session;
// 2. 安全讀取
if (session["LoginUser"] is UserInfo user)
{
context.Response.ContentType = "application/json";
context.Response.Write($"{{\"user\":\"{user.Account}\",\"role\":\"{user.Role}\"}}");
}
else
{
context.Response.StatusCode = 401;
context.Response.Write("{\"error\":\"未登入或 Session 逾期\"}");
}
}
}
// 簡易用戶模型
public class UserInfo
{
public string Account { get; set; }
public string Role { get; set; }
}
}
<%@ WebHandler Language="C#" Class="MyApp.Handlers.SecureHandler" %>
| 錯誤現象 | 原因 | 修正 |
|---|---|---|
| context.Session 為 null | 未實作 IRequiresSessionState / IReadOnlySessionState | 在類別宣告加上介面 |
| Session 值永遠為空 | Cookie 未正確傳遞(跨域、SameSite、Secure 設定) | 檢查瀏覽器開發者工具 Application → Cookies,確認 ASP.NET_SessionId 存在 |
| Session 變數型別轉換失敗 | 存入時為 UserInfo,取出時直接轉 string | 使用 `as` 或模式比對 `is UserInfo u` 安全轉型 |