ASP.NET 在 global.asax 實作 session timeout 後的 redirect
在傳統的 asp 可以用 include 的方式,但在 asp.net 還是寫在 global.asax 或者用實作 IHttpModule 的方式來處理
其中比較需要注意的是,通常直覺會把這檢查寫在 Application_BeginRequest() 裏頭,但是在 Application_BeginRequest() 裡面,其實還無法存取 session 資料,所以不管怎麼檢查都是會有問題,需要改寫在 Application_AcquireRequestState() 裏頭。
Sub Application_AcquireRequestState(ByVal sender As Object, ByVal e As EventArgs) If HttpContext.Current.Request.FilePath.ToLower().Contains("redirect.html") = True Or _ HttpContext.Current.Request.FilePath.ToLower().Contains("default.aspx") = True Then Return End If Dim bFindKeyYear As Boolean = False Try If Session("Year") IsNot Nothing Then bFindKeyYear = True Else End If Catch ex As Exception End Try If bFindKeyYear = False Then HttpContext.Current.Response.Redirect("redirect.html") End If End Sub
如果是用 IHttpModule 的方式來處理的話,就是開 App_Code 目錄,在底下建立 class file 實作
Imports Microsoft.VisualBasic Imports System.Web Public Class Module_httpmodule Implements IHttpModule Public Sub New() End Sub ' In the Init function, register for HttpApplication ' events by adding your handlers. Public Sub Init(ByVal application As HttpApplication) _ Implements IHttpModule.Init AddHandler application.AcquireRequestState, AddressOf Me.Application_AcquireRequestState End Sub Public Sub Dispose() Implements System.Web.IHttpModule.Dispose End Sub Private Sub Application_AcquireRequestState(ByVal source As Object, ByVal e As EventArgs) ' Implements here End Sub End Class
然後要改一下 web.config 加上
<configuration> <system.webServer> <modules> <add name="Module_httpmodule" type="Module_httpmodule"/> </modules> </system.webServer> </configuration>
關於 global.asax 可以處理的 events 或說 asp.net application 整個 life cycle 也可以參考https://www.cnblogs.com/zzyyll2/articles/1102214.html
Original link: Phanix's Blog