Sunday, January 31, 2010

ASP.NET Logout on Session Expire

Here's a way to enable logout after session has expired in your ASP.NET pages.

Let us begin with the sessionState tag inside the web.config file:

    <sessionState mode="InProccookieless="falsetimeout="30"/>

Make sure to place it inside the system.web tag. For the attributes, we use InProc mode to store the session on the local computer, cookieless is set to false which means it will store the session as cookies (if you set this to true, you will get some jumbled alphanumeric characters in your webpage's URL) and finally timeout which has a numeric value equal to how long you want your session in minutes before it expires.

For more information on sessionState attributes, check out msdn:

Now the snippet above alone will not make your page redirect automatically to your logout page after session has expired. We still need human intervention to enable that. So we add this next logic to the Master Page's page_load event (or to all pages of a website if you're not using master pages):

protected void Page_Load(object sender, EventArgs e)
    //1st: Every postback should pass through this code.
    //     Make a decision statement to check if user has already logged in.
    if (user has already logged in)
        //2nd: Check your user session. 
               If session is null (expired) then continue.
        if (Session["user_session"] == null)
            //3rd: Clear all sessions, data, connections, etc. (optional)
                   Redirect to logout page.
            Page.Response.Redirect("logout_page", true);

Handling session expiration is required for web pages which uses sessions to store data so you won't encounter the object reference not set to an instance of an object error should your session objects expire.



  1. thank you man
    in shaa allah in your hasanat

  2. Hey keep posting such good and meaningful articles.