Monday, May 11, 2009

ASP.Net session expired Handling

Step 1: Create the SessionExpired.cs file into APP_CODE folder and write the code below:

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

///
/// Summary description for SessionExpired
///
public class PageBase : System.Web.UI.MasterPage
{
    public PageBase()
{
//
// TODO: Add constructor logic here
//
}
    protected override void OnPreRender(System.EventArgs e)
{
    base.OnPreRender(e);
   
    if (Context.Session.IsNewSession == true) {
        string strCookieHEader = Page.Request.Headers["Cookie"];
        if ((strCookieHEader != null)) strCookieHEader = strCookieHEader.ToLower();
        if ((strCookieHEader != null) && strCookieHEader.IndexOf("asp.net_sessionid") >= 0) {
            if (Page.Request.IsAuthenticated == true) {
                System.Web.Security.FormsAuthentication.SignOut();
            }
            Page.Response.Redirect("~/login.aspx?Id=1");
        }
    }
}
}


Step 2: Refer this .cs file into your master page code behind(aspx.cs). write "PageBase" instead of "System.Web.UI.MasterPage" like this

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;

public partial class MasterPage1: PageBase
{
   
    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            
           
        }
       
    }

    
    
}

Conclusion:
Session state maintanance is the tidious task for developer.Because of this code programmer can handle the session state and redirect to login Page with the message of "Session has expired.." by the view state management.

Feel free to write mail...
My Mail Address: karthikexp@gmail.com