The Will Will Web

記載著 Will 在網路世界的學習心得與技術分享

在 Global.asax 中如何檢查 Session 是否啟用

我們開發網站的時候,一般都會在 Global.asax 中的 Application_Error 事件擷取整個網站應用程式(Web Application)未經處理的例外事件(Unhandled Exception),並將一些可提供偵錯的資訊整理成 Email 寄給網站維護相關人員。

其中 Session 物件通常包含許多可供錯誤驗證的資訊,不過有些客戶的網站並未使用到 Session 物件,當不使用的時候,我們會在 web.config 中的 <system.web> 區段下設定:

<pages enableSessionState="false">

而當不啟用 Session 的時候,我們通常直覺上會嘗試直接用以下語法檢查 Session 是否存在:

if(this.Session != null)
{
   ......
}

不過,這樣的寫法 ( this.Session ) 卻會引發以下例外狀況:

'this.Session' threw an exception of type 'System.Web.HttpException'

基於 ASP.NET 的設計,在 Global.asax 中使用 this.Session 其實用的是 HttpApplication.Session 屬性,而當 Session 功能被關閉後,使用這個屬性就會直接導致例外狀況!

要解決這個問題,只要改用 HttpContext.Current.Session 即可解決此問題,當 Session 功能被關閉後,使用 HttpContext.Current.Session 會回傳 null,這樣在 if 判斷式才不會引發例外事件。

if( HttpContext.Current.Session != null)
{
   ......
}

相關連結

留言評論