Tutorial :Checking if Session has Timed Out



Question:

This is my base class for all pages except EndSession.aspx

override protected void OnInit(EventArgs e)  {    base.OnInit(e);      if (Context.Session != null)         {             //check the IsNewSession value, this will tell us if the session has been reset.             //IsNewSession will also let us know if the users session has timed out             if (Session.IsNewSession)             {                //now we know it's a new session, so we check to see if a cookie is present                 string cookie = Request.Headers["Cookie"];                 //now we determine if there is a cookie does it contains what we're looking for                if ((null != cookie) && (cookie.IndexOf("ASP.NET_SessionId") >= 0) )//&& !Request.QueryString["timeout"].ToString().Equals("yes"))                 {                     //since it's a new session but a ASP.Net cookie exist we know                     //the session has expired so we need to redirect them                       Response.Redirect("EndSession.aspx?timeout=yes");                 }             }         }     }   

But on EndSession I try to navigate back to, say default.aspx, and then this code above just redirects be back to EndSession.aspx.

So for better clarification: Step 1: Go to mypage.aspx Step 2: Wait for timeout Step 3: try to navigate away Step 4: get redirected to EndSession.aspx Step 5: try to navigate away Step 6: GoTo set 4

Setp 6 should be actually being able to navigate away...

(if needed pelase ask for further clarification)

Any ideas?

THANKS!!!


Solution:1

I got rid of the basepage that I had originally.

Put this in the Session_Start of Global.asax

void Session_Start(object sender, EventArgs e)   {      string cookie = Request.Headers["Cookie"];      // Code that runs when a new session is started      if ((null != cookie) && (cookie.IndexOf("ASP.NET_SessionId") >= 0))//&& !Request.QueryString["timeout"].ToString().Equals("yes"))        {          if(Request.QueryString["timeout"] == null || !Request.QueryString["timeout"].ToString().Equals("yes"))              Response.Redirect("Default.aspx?timeout=yes");      }  }  

Put this on the Defualt.aspx page:

 if (!IsPostBack)      {          if (Request.QueryString["timeout"] != null && Request.QueryString["timeout"].ToString().Equals("yes"))          {              Response.Write("<script>" +                 "alert('Your Session has Timedout due to Inactivity');" +                 "location.href='Default.aspx';" +                 "</script>");          }      }  

This solution works even when the timeout occurs on the Default.aspx page

The discusion for the solution I used is posted here: How to stop basepage from recursivly detecting session timeout


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »