title: ASP.Net Session Timeout detection: Is Session.IsNewSession and SessionCookie detection the best way to do this?
body: <p>When my ASP.Net session times out (and forms authentication as well) and I try to hit a page, I am automatically redirected to my default login.aspx page. </p>
  
  <p>Before the page loads I need to determine whether this is a timeout situation and if so - redirect to timeout.aspx.</p>
  
  <p>The articles below specify that if IsNewSession is true, and a sessionID cookie exists - then you have a timeout situation.</p>
  
  <p>However in my testing I have the situation where I timeout and try to log back in again and IsNewSession is equal to true and the sessionId cookie is still hanging around (because it stays for a entire browser session), therefore it says I've timed-out again when I'm just trying to log back in.</p>
  
  <p>Is there a better way to do all this?</p>
  
  <p>Technique is decribed <a href="http://www.eggheadcafe.com/articles/20051228.asp" rel="noreferrer">here</a> and <a href="http://blogs.msdn.com/nikhiln/archive/2007/06/21/detecting-session-timeout-in-asp-net-2-0-web-applications.aspx" rel="noreferrer">here</a>.</p>
  
  <p>In my 'global.asax' file I have:</p>
  
  <pre><code>void Application_PreRequestHandlerExecute(object sender, EventArgs e)
  {
          // Check if session state is enabled in web.config
          if (Context.Session == null) return;
  
          if (Session["user"] == null) 
          {
              if (Session.IsNewSession)
              {                    
                  HttpCookie sessionCookie = Request.Cookies["ASP.NET_SessionId"];
                  if ((null != sessionCookie) &amp;&amp; !string.IsNullOrEmpty(sessionCookie.Value))
                  {
                      /* Session Timeout! */
                      FormsAuthentication.SignOut(); //just in case not done yet
                      Session.Abandon();
                      Response.Redirect("timeout.aspx");
                  }
                  else
                  {
                      // Cookie didn't exist - must be a brand new login
                      return;
                  }
              }
              else
              {
                  // If there is no session data and the session is not new then it must be the postback of the login screen.
                  if ((HttpContext.Current.Request.Path.ToLower().LastIndexOf("/login.aspx") &gt;= 0) &amp;&amp; (Request.HttpMethod == "POST"))
                  {
                      return;
                  }
              }
          }    
  }
  </code></pre>