Redirect to login page after session timeout

I found several similar questions, but no one gave me what I really needed.

Here is what I added to my web.config to handle the expiration of a user session:

 <sessionState mode="InProc" timeout="1" /> 

After 1 minute, the Session_End event from Global.asax raised:

 Sub Session_End(ByVal sender As Object, ByVal e As EventArgs) Response.Redirect("Login.aspx") End Sub 

This does not work because:

 Response is not available in this context. 

(By the way, this question received an answer saying that this is normal, and he received upvotes).

I don't want anything fancy. I just want an easy way to redirect the user to the login page when the session expires. It's all.

Thanks.

+4
source share
4 answers

Session_End is a server event, that is, it is fired on a web server and has nothing to do with a client request. This is why the request is not available.

You have two options in this question:

  • In each client request, verify that a specific session variable is set. If this is not the case, it means that the previous session has expired and the new session should be filled. (I assume that is why you want to check for session expiration)

  • Have a javascript call on the client that periodically returns to the server to check if the session is valid. If the session has expired, you can alert the user to end the session.

NTN

+2
source

Description

You can use the Page_Init event in global.asax

Example

 Protected Sub Page_Init(sender As Object, e As EventArgs) If Context.Session IsNot Nothing Then If Session.IsNewSession Then Dim newSessionIdCookie As HttpCookie = Request.Cookies("ASP.NET_SessionId") If newSessionIdCookie IsNot Nothing Then Dim newSessionIdCookieValue As String = newSessionIdCookie.Value If newSessionIdCookieValue <> String.Empty Then ' This means Session was timed Out and New Session was started Response.Redirect("Login.aspx") End If End If End If End If End Sub 

Additional Information

+3
source

Check expired sessions on every Page_Init event. If there are too many pages for this check, this is what I usually do:

  • I create a base class and inherit from System.Web.UI.Page.
  • Write my redirection logic in the Page_Init event of my base class.
  • The rest of my pages inherit from this base class.

Good luck.

0
source
 protected void Page_Init(object sender, EventArgs e) { if (Context.Session != null) { if (Session.IsNewSession) { HttpCookie newSessionIdCookie = Request.Cookies["ASP.NET_SessionId"]; if (newSessionIdCookie != null) { string newSessionIdCookieValue = newSessionIdCookie.Value; if (newSessionIdCookieValue != string.Empty) { // This means Session was timed Out and New Session was started Response.Redirect("Login.aspx"); } } } } } 
0
source

Source: https://habr.com/ru/post/1435142/


All Articles