Handling session timeout when inactive ajax call to C # mvc controller

When calling a function from ajax. The program thread does not recognize the expired session, i.e. Not redirected to login page. Instead, it saves the record. I work in C # .net mvc. So how can I handle a session during an ajax call. Here I gave my codes.

$.ajax({ type: "POST", url:'/Employee/SaveEmployee', data: { Location:$("#txtLocation").val(), dateApplied:$("#txtDateApplied").val(), Status:$("#ddStatus").val(), mailCheck:$("#ddMailCheck").val(), ... ... ... }, success: function (result) { }, error: function (msg) { } }); 

Here is the controller

 [Authorize] public string SaveEmployee(string Location, string dateApplied, string Status, string mailCheck, ...) { objEmpMain.FirstName = firstName; objEmpMain.LastName = lastName; objEmpMain.Initial = Initial; objEmpMain.Address1 = Address; ... ... ... } 
+7
source share
2 answers

The result of your AJAX call will still seem successful (although, don’t worry, it will not actually execute your action method) and call the success handler. This is because you expect HTML, and that is what you get (although most likely your HTML code is most likely your login page, not the HTML you wanted). As an aside, if you were expecting JSON (using dataType:'JSON' ), it would dataType:'JSON' an error because it would be parsing HTML as JSON.

What you need to do is prevent FormsAuth from redirecting the login page for AJAX requests. AuthorizeAttribute now correctly returns NotAuthorizedResult , which sends an HTTP 401 HTTP autoresponder to the client, which is ideal for your AJAX client.

The problem is that the FormsAuth module checks the StatusCode and, if it is 401, it redirects. I solved this problem this way:

1) Create your own derived type, AuthorizeAttribute , which puts the flag in HttpContext.Items to let me know that authorization has failed and I must force 401, not a redirect:

 public class AjaxAuthorizeAttribute : AuthorizeAttribute { /// <summary> /// Processes HTTP requests that fail authorization. /// </summary> /// <param name="filterContext">Encapsulates the information for using <see cref="T:System.Web.Mvc.AuthorizeAttribute"/>. The <paramref name="filterContext"/> object contains the controller, HTTP context, request context, action result, and route data.</param> protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { if (filterContext.HttpContext.Request.IsAjaxRequest()) filterContext.HttpContext.Items["AjaxPermissionDenied"] = true; base.HandleUnauthorizedRequest(filterContext); } } 

2) Add to your Global.asax.cs file:

  protected void Application_EndRequest(Object sender, EventArgs e) { if (Context.Items["AjaxPermissionDenied"] is bool) { Context.Response.StatusCode = 401; Context.Response.End(); } } 

3) Add a statusCode handler to your jQuery AJAX setup:

 $.ajaxSetup({ statusCode: { 401: function() { window.location.href = "path/to/login"; } } }); 

4) Change the controllers or actions in which you want this behavior to use AuthorizeAttribute - AjaxAuthorizeAttribute :

 [AjaxAuthorize] public string SaveEmployee(string Location, string dateApplied, string Status, string mailCheck, ...) { objEmpMain.FirstName = firstName; objEmpMain.LastName = lastName; objEmpMain.Initial = Initial; objEmpMain.Address1 = Address; ... ... ... } 
+23
source

I would suggest you use StatusCode = 306. I met some problem when I use 401.IIS refers to 401, different from what I understand. 306 works great for me.

Sincerely.

+1
source

All Articles