Thursday, April 14, 2005
ASP.Net: Redirecting user when their session expires
This is tricky since there are two issues: the user's forms authentication ticket might have expired, and also the session expires on the server. You can't use global.asax's Session_End event, since that happens on the server, even if there is no current request from the user, so you cannot redirect them.
Here is one way around the problem for v1.1 that I found here:
Q: How do I detect a session has expired and redirect it to another page?
A: It's a much requested feature, and unfortunately there is no easy way to do it right now. We will look into in the next major version. In the meantime, if you are using cookie, you can store a marker in your cookie so you can tell the difference between "fresh browser + new session" and "old browser + expired session". Below is a sample code that will redirect the page to an expired page if the session has expired.
void Session_OnStart(Object sender, EventArgs e)
HttpContext context = HttpContext.Current;
HttpCookieCollection cookies = context.Request.Cookies;
if (cookies["starttime"] == null) // Fresh session
HttpCookie cookie = new HttpCookie("starttime", DateTime.Now.ToString());
cookie.Path = "/"; context.Response.Cookies.Add(cookie);
else // Expired session