Detecting Session Timeout And Redirect To Login Page In ASP.NET

This is example of Detecting Session Timeout and Redirect to Login Page in ASP.NET, session timeout occurs when user is idle for the time specified as in web.config file.

For this i’ve set time out value in web.config to 1 minute.

In web.config file, set the sessionstate mode to inproc and authentication mode to Forms

<system.web>
<compilation debug="true"/>
<authentication mode="Forms"/>
<sessionState mode="InProc" cookieless="false" timeout="1">
</sessionState>
</system.web>

I've created three pages in this example , one is login page , when session expires , i redirect to this page , one is navigation page where i'll check if session is valid or not , if it is valid than only user will see this page other wise he gets redirected to login page.

Add Global.asax class file in root of your application or website. 
This method works only if Global.asax is present in application.

Write below mentioned code in Page_Init event of the page where we want to check for session timeout. 

we can also put this code in in a class and inherit all pages of application from this class acting as base class for all pages to check for session timeout.

protected void Page_Init(object sender, EventArgs e)
    {
        if (Context.Session != null)
        {
            if (Session.IsNewSession)
            {
                HttpCookie newSessionIdCookie = Request.Cookies["ASP.NET_SessionId"];
                if (newSessionIdCookie != null)
                {
                    string newSessionIdCookieValue = newSessionIdCookie.Value;
                    if (newSessionIdCookieValue != string.Empty)
                    {
                        // This means Session was timed Out and New Session was started
                        Response.Redirect("Login.aspx");
                    }
                }
            }
        }
    }


This article is part of this article.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s