Redirect To Login Page On Session Time Out In ASP.NET MVC

In this blog, you will learn how to redirect to the Login page when a session is timed out in ASP.NET MVC.
Let's start.
 
Create a new class and inherit AuthorizeAttribute.
  1. public class SessionExpireFilterAttribute : AuthorizeAttribute    
Override the method HandleUnauthorizedRequest to newly created class.
 
This method checks if the session is new or user session is null. If session is null or user session is null, then
it checks if the IsAjaxRequest is present or not. If it is an AJAX request, it clears the content of HttpContext response and adds one flag with the name "AjaxPermissionDenied". Then, it sets the value True, and else redirects the result to the login page.
  1. protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)  
  2. {  
  3.   HttpContext ctx = HttpContext.Current;  
  4.   // check if session is supported  
  5.   if (ctx.Session != null)  
  6.   {  
  7.     // check if a new session id was generated  
  8.      if (ctx.Session["UserId"] == null || ctx.Session.IsNewSession)  
  9.        {  
  10.         //Check is Ajax request  
  11.          if (filterContext.HttpContext.Request.IsAjaxRequest())  
  12.          {  
  13.            filterContext.HttpContext.Response.ClearContent();  
  14.            filterContext.HttpContext.Items["AjaxPermissionDenied"] = true;  
  15.          }  
  16.          // check if a new session id was generated  
  17.          else 
  18.          {  
  19.             filterContext.Result = new RedirectResult("~/Account/Login");  
  20.          }  
  21.       }  
  22.   }  
  23.   base.HandleUnauthorizedRequest(filterContext);  
  24. }  
Now, check "AjaxPermissionDenied" flag on Application_EndRequest in Global.asax and based on that, set the response StatusCode. 
  1. protected void Application_EndRequest()  
  2. {  
  3. if (Context.Items["AjaxPermissionDenied"is bool)  
  4.  {  
  5.    Context.Response.StatusCode = 401;  
  6.    Context.Response.End();  
  7.  }  
  8. }  
Now, handle StatusCode on AjaxError as Global level layout page or View. 
  1. $(document).ajaxError(function (xhr, props) {   
  2. if (props.status === 401) {  
  3.    window.location.href = '@Url.Action("Login","Account")';  
  4.   }  
  5. });