Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect to login page after session timeout

I have found some similar questions but none gave me what I really need.

Here is the thing, I have added this to my web.config to handle user session expiration:

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

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

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

This doesn't work, because:

Response is not available in this context.

(By the way, this question got an anwswer telling that this is ok and it got upvotes).

I don't want nothing fancy. I just want a simple way to redirect the user to the login page when the session time expires. That's all.

Thank you.

like image 697
gabsferreira Avatar asked Sep 19 '12 20:09

gabsferreira


Video Answer


2 Answers

Description

You can use the Page_Initevent in the global.asax

Sample

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

More Information

  • Detecting Session Timeout And Redirect To Login Page In ASP.NET
like image 166
dknaack Avatar answered Oct 11 '22 20:10

dknaack


Session_End is a server-side event, meaning it is triggered on the web server and has nothing to do with a request by the client. This is why the Request is unavailable.

You have two choices in this matter:

  1. On each client request, check if a specific Session variable is set. If it is not, it means the previous Session has expired and the new Session must be populated. (I am assuming this is why you want to check for Session expiration)

  2. Have a javascript call on the client that periodically goes back to the server to check if the Session is still valid. If the Session has expired, you can redirect the user to the login page.

samples of different redirect methods

location.href = "login.aspx";
// or you can use 
location.assign("login.aspx");
//for redirecting without storing in history
location.replace("login.aspx")

Don't forget to add ?ReturnUrl=[current url] to the login redirect path.

HTH

like image 28
Shai Cohen Avatar answered Oct 11 '22 20:10

Shai Cohen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!