How to do auto logout and redirect to login page when session expires in asp.net using C#?

Category > ASP.NET || Published on : Wednesday, June 17, 2015 || Views: 4126 || auto logout and redirect to login page when session expires How to do auto logout and redirect to login page when session expires asp.net tricks


Introduction

In day to day applications, we need to maintain the session expiration time say for example 45 minutes and this configuration item we can do with web.config file or in IIS. But here, application should redirect to login page automatically when session expires.

Step 1: Configure session time, First configure the session timeout value in web.config file as like below, here I’m configuring the session timeout value as 3 minutes for this sample code goes below

<system.web>

<sessionState mode="InProc" timeout="3"></sessionState>

</system.web>

Step 2:Create Pagebase class

public class PageBase : System.Web.UI.Page

{

protected override void OnPreRender(EventArgs e)

{

    base.OnPreRender(e);

    AutoRedirect();

}

public void AutoRedirect()

{

int int_MilliSecondsTimeOut = (this.Session.Timeout * 60000);

string str_Script = @"

   <script type='text/javascript'> 

    intervalset = window.setInterval('Redirect()'," + int_MilliSecondsTimeOut.ToString() + @");

    function Redirect()

    {

       alert('Your session has been expired and system redirects to login page now.!\n\n');

       window.location.href='/login.aspx'; 

    }

</script>";

ClientScript.RegisterClientScriptBlock(this.GetType(), "Redirect", str_Script);

}

}

Above AutoRedirect function will be used to redirect the login page when session expires, by using javascript window.setInterval, This window.setInterval executes a javascript function repeatedly with specific time delay. Here we are configuring the time delay as session timeout value. Once it’s reached the session expiration time then automatically executes the Redirect function and control transfer to login page.

Step 3: In testAutologout page, we need to inherit the PageBaseclass as like below also same thing we need to inherit wherever required this functionality.


using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

namespace TestWeb

{

 public partial class testAutoLogout : PageBase

 {

    protected void Page_Load(object sender, EventArgs e)

    {

    }

 }
}

Once application reached session expiration time if suppose there is no action performed by user, it shows the warning message as like below and if clicks the Ok in the message box it redirects to login.aspx page.