Automatic redirect upon session timeout using ASP.NET MVC and Javascript

Recently (Not so long ago, more like 10 mins ago) my asked me to automatically redirect the user to the login screen after session is expired. I googled it, found 2 ways. One works well with NON-AJAX websites and it is the simplest.

 <meta http-equiv="refresh" content="@FormsAuthentication.Timeout.TotalSeconds;url=@FormsAuthentication.LoginUrl" />

If you are making a site like facebook, then using the above method would cause number of users to decrease from 1 billion to 0. Why? because this method counts only full page refreshes, not ajax requests.

So, next method is using Javascript and thanks to this blog. automatic-redirect-upon-session-timeout-using-javascript/

Following is the same logic with MVC Forms authentication specific Razor code.

First, the web.config Forms Auth entries.


   <authentication mode="Forms">

      <forms loginUrl="~/Login" slidingExpiration="true" timeout="20" />



Next, the javascript.

<script src="~/Scripts/jquery.min.js"></script>


var timeout = @FormsAuthentication.Timeout.TotalMilliseconds; // 20 minutes

var wintimeout;

function SetWinTimeout() {
    wintimeout =  window.setTimeout( "window.location.href='@FormsAuthentication.LoginUrl';",                          timeout); // In millisecods

$('body').click(function() {  
  //when user clicks remove timeout and reset it


That's all. This works for AJAX and NON-AJAX calls seamlessly.

Popular posts from this blog

Print a sales receipt using a thermal printer with C# for POS Application

Could not create SSL/TLS secure channel - Fixed