How to check session timeout before accessing session item ?


Here, I am considering that all you know how session maintained 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 br="br"> SessionHdr ="";
}
if (SessionHdr != null && string.IsNullOrEmpty(SessionHdr) != false)
{
// Do your operation here
Response.Redirect("sessiontimeout.htm");
}
}
}
}










Comments

Popular posts from this blog

Difference between Parse/TryParse/ParseExact/TryParseExact

Benefits of Test Driven Development (TDD)

Version history of C#