Friday, October 23, 2009

Handling Session Timeouts

With new technology making the web a viable option for more and more applications, we are now seeing the web browser take over for the traditional desktop. Developers making this transition, quickly learn about some of the key differences between the two paradigms.  One of the issues they are often forced to deal with is Session expiration.  Out of the box, ASP.NET and IIS typically allow only 20 minutes of idle time before the session expires. This can be configured, but knowing that the session expired, or redirecting to a particular page often comes in handy.  One way to do this is to add a cookie during the Session_Start method of the global.ascx.cs file, and then check for that same cookie the next time a session is created.  If the cookie is there, the session either timed out, or was reset.

Here is an example:

protected void Session_Start(Object sender, EventArgs e)
 {
     //Check if there is a cookie from when the session started.
     //If not, the session has not been started yet,
     //so add the cookie.
     HttpContext context = HttpContext.Current;
     HttpCookieCollection cookies = context.Request.Cookies;
     HttpCookie SessionCookie = cookies["SessionStarted"];
     if (SessionCookie == null)
     {
         HttpCookie cookie = new HttpCookie("SessionStarted", DateTime.Now.ToString());
         cookie.Path = "/";
         context.Response.Cookies.Add(cookie);
     }
     else
     {
         //If there was a cookie, but we are in this method starting a session
         //Then the session must have expired or been reset.

         //TODO: Do something useful with this info, log it, etc.
         //update the cookie with the new session start time
         cookies.Remove("SessionStarted");
         SessionCookie.Value = DateTime.Now.ToString();
         context.Response.Cookies.Add(SessionCookie);

         //Redirect to the whatever page you want to handle this situation.
         //An error page, login page, etc.
         context.Response.Redirect("~/Login.aspx", true);
     }
 }
 
 ---
thnx...enjoy programming.

No comments:

Post a Comment