.net – Asp.net session expiry redirect to login page

.net-2.0asp.net-2.0netsession

What is the best way to redirect to the login page when the session expires. I'm using

sessionState mode="InProc"

Can I set this in the web.config file?

Best Answer

The trick to remember about the session expiration is that this happens in the the worker process running behind the scenes and there is no direct way to notify the user without going back to the server to check the state of things.

What I do is I have the page register a Javascript block that will redirect the user to the login page again after the designated timeout:

Page.ClientScript.RegisterStartupScript(Me.GetType, "TimeoutScript", 
"setTimeout(""top.location.href = '~/Login.aspx'""," &
 ConfigurationManager.AppSettings("SessionTimeoutMilliseconds") & ");", True)

You'll notice that I have the actual milliseconds stored in my web.config file so that I can adjust the timeout length as needed.

Using this, combined with the typical Session_End event in the Global.asax file makes a pretty clean way of handling session timeouts in my web apps.