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.
- 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.
- protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
- {
- HttpContext ctx = HttpContext.Current;
-
- if (ctx.Session != null)
- {
-
- if (ctx.Session["UserId"] == null || ctx.Session.IsNewSession)
- {
-
- if (filterContext.HttpContext.Request.IsAjaxRequest())
- {
- filterContext.HttpContext.Response.ClearContent();
- filterContext.HttpContext.Items["AjaxPermissionDenied"] = true;
- }
-
- else
- {
- filterContext.Result = new RedirectResult("~/Account/Login");
- }
- }
- }
- base.HandleUnauthorizedRequest(filterContext);
- }
Now, check "AjaxPermissionDenied" flag on Application_EndRequest in Global.asax and based on that, set the response StatusCode.
- protected void Application_EndRequest()
- {
- if (Context.Items["AjaxPermissionDenied"] is bool)
- {
- Context.Response.StatusCode = 401;
- Context.Response.End();
- }
- }
Now, handle StatusCode on AjaxError as Global level layout page or View.
- $(document).ajaxError(function (xhr, props) {
- if (props.status === 401) {
- window.location.href = '@Url.Action("Login","Account")';
- }
- });