Introduction
Session management is a powerful concept in ASP.net. It’s provides 4 techniques to manage the session.
- In Proc (Default)– Most applications will use.
- State server
- SQL server – For scalable scenarios like web clustering etc.
- Custom (very rare)
The beauty of session management in asp.net is without changing current coding we can use these management techniques in administration mode.
Please refer my blog entry for more details.
Background
In any of the above cases, the session supposed to be timeout. It will handle by the asp.net runtime, which we can set in the web.config <sessionState timeout="1" />
. Default timeout is 20 mins. Which means after 20 min session will become abandon and if you are not correctly handle it will leads to system crash. What general recommendation is, always check null
of the session item that you’re going to refer. But in most user oriented application, we should notify the user that ,"Hello your current session has expired, what do you want to do?"
How to achieve this?
Using the code
If use In-Proc, it will automatically fire up session_end
event which you can handle in Global.asax
file. In rest of techniques this event will be ignored.
There are some workarounds to overcome this, but I’ll illustrate a simple trick, a pattern called “heartbeat”, that I’ve used in couple of my projects (especially in non AJAX applications).
In a nutshell, application will poll elapse time from the last post back and when it reaches to the time setup for session timeout, it will redirect to a page in which completely destroy the session.
Without talking much let’s see how it is working.
- By considering the session time out ,we will generate a javascript and register to the page. As you can see in the following code snippet, I’ve attached
logout()
to the windows.onload
event. (In non AJAX case this is always true. ) After time has expired it will redirect to the Timeout.aspx page, where user can retry the application.
ClientScriptManager cm = Page.ClientScript;
if(!cm.IsClientScriptBlockRegistered(Page.GetType(),"session_timout"))
{
StringBuilder sb = new StringBuilder();
sb.Append("function logout(){");
sb.Append("alert('Session has expired');");
sb.Append("window.location.href='http://www.codeproject.com/Timeout.aspx';");
sb.Append("}");
sb.Append("window.onload = function(){var t=setTimeout(\"logout()\",");
sb.Append(Session.Timeout * 1000*60);
sb.Append(");}");
cm.RegisterStartupScript(Page.GetType(), "session_timout", sb.ToString(), true);
}
- Set up the Session Time out in the web.config
<system.web>
...
<sessionState timeout="1" />
...
</system.web>