2024/10/24

[ASP.NET MVC] 解決在 WebAPI 讀取不到 Session 值的問題

環境

  • ASP.NET MVC 5
  • .NET Framework 4.7.2+

問題

原本有個設定值以 Cookie 為存取來源, 但因應安全理由改寫成 Session 來存取, 卻在 WebAPI 存取時發生讀取不到 Session 的內容。

在 ASP.NET Core MVC 反而簡單, 只要 services.AddSession()app.UseSession() 即搞定。

目前還是有許多不是 .NET Core 的專案,記錄一下以供未來翻查用。

解決方法

修改 Global.asax.cs 檔案

protected void Application_PostAuthorizeRequest()
{
    // WebApi SessionState
    bool isWebApiRequest = HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.StartsWith("~/api");
    if (isWebApiRequest) HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
}

參考資料