How to check session timeout before accessing session item?

Here, I am trying to highlight "object reference not set" issue due to session time out or if session timed out than decide your next operation keeping in mind that reader know how session maintain in ASP.NET

Purpose: To avoid object "Object reference not set" exception that comes when trying to access session element after timeout. 

Prescribed Solution: It's hard to check session existence in every step. So, what we can do is just check the session existence with the help of session id and one property (IsNewSession: This property will return true if new session initiated). We can implement this check either on ASPX page level or master page.

protected void Page_Init(object sender, EventArgs e)
{

if (Context.Session!=null)

{

if (Session.IsNewSession)

{

string SessionHdr =String.Empty;

if (Session.IsCookieless)

SessionHdr = Request.Headers["AspFilterSessionId"];

else

{

SessionHdr = Request.Headers["Cookie"];

if (SessionHdr.IndexOf("ASP.NET_SessionId")<0)

SessionHdr ="";

}

if (SessionHdr != null && string.IsNullOrEmpty(SessionHdr) != false)

{

// Do your operation here

Response.Redirect("sessiontimeout.htm");

}

}

}

}

-- Please try it and if you notice any issue than post your feedback

Ref : http://aspalliance.com/520_Detecting_ASPNET_Session_Timeouts.all

Comments

Popular posts from this blog

Difference between Parse/TryParse/ParseExact/TryParseExact

Benefits of Test Driven Development (TDD)

Version history of C#