Problem: An ASP.NET 2.0 web application needs to detect a session timeout condition so that the user can be redirected to a different page and / or an error message is displayed.
Solution: There are three ways of approaching this problem, starting off with the simplest one to the most complicated one. So, here it goes:
- Using Session[“xxx”] value to determine the session timeout: This is a “quick and dirty” hack that can be introduced into an application to figure out whether a timeout has occured. We need to do two things here.
First, in Global.asax, create your own GUID and put it in the session object,
voidSession_Start(object sender, EventArgs e)
// Code that runs when a new session is started
Session[“CustomSessionId”] = Guid.NewGuid();
Second, BasePage.cs which would have inherited Page, in PageLoad() event, check whether the Session[“CustomSessionId”] == null, if it IS null, it means that the session was timed-out and AspNet runtime cleared it out.
if( Session[“CustomSessionId”] == null)
Using a combination of Session.IsNewSession and Request.Cookies collection: Leveraging the behavior of ASP.NET runtime, we can check whether the Session.IsNewSession flag is true, if its true and we find that Request.Cookies[“ASP.NET_SessionId”] has a valid value, it means that a timeout occured and a new request was generated by the runtime. This code fragment can be inserted into the OnInit(…) method in the BasePage class so that it applies across the application.
protected override void OnInit(EventArgs e)
if (Context.Session != null)
//check whether a new session was generated
//check whether a cookies had already been associated with this request
HttpCookie sessionCookie = Request.Cookies[“ASP.NET_SessionId”];
if (sessionCookie != null)
string sessionValue = sessionCookie.Value;
// we have session timeout condition!
Session[“IsSessionTimeOut”] = true;
WARNING:- We will have to wireup the “void Session_Start(object sender, EventArgs e)” method in the Global.asax to use the Session.IsNewSession meaningfully. ASP.NET 2.0 runtime is a bit weird in the sense that it will always return the value of Session.IsNewSession as true in case the Event is not wireup!
Using HTTP Module: Arguably the most complex but robust way to tackle this situation. I would rather not go into this as this carries the risk of opening security holes in the HTTP stream