ASP.NET MVC forces an AJAX request be redirected to the login page when the FormsLogin session is no longer active ASP.NET MVC forces an AJAX request be redirected to the login page when the FormsLogin session is no longer active ajax ajax

ASP.NET MVC forces an AJAX request be redirected to the login page when the FormsLogin session is no longer active


Set it up in the Application_EndRequest() method of the Global.asax

You can check to see if the request is an ajax request and also check if it is sending an HTTP redirect (302) if it is, then we actuall want to send a 401.

protected void Application_EndRequest() {            var context = new HttpContextWrapper(Context);            // If we're an ajax request, and doing a 302, then we actually need to do a 401            if (Context.Response.StatusCode == 302 && context.Request.IsAjaxRequest()) {                Context.Response.Clear();                Context.Response.StatusCode = 401;            }        }

Then in your client code, in a globally accessible area:

MyNamespace.handleAjaxError = function (XMLHttpRequest, textStatus, errorThrown) {    if (XMLHttpRequest.status == 401) {        // perform a redirect to the login page since we're no longer authorized        window.location.replace("logout path");    }        } else {        MyNamespace.displayGeneralError();    }};  $.ajax({  type: "GET",  url: userAdmin.addUserActionUrl,  success: userAdmin.createUserEditorDialog,  error: MyNamespace.handleAjaxError });


With current versions of ASP.NET MVC there is a much easier solution to fix this issue: Response.SuppressFormsAuthenticationRedirect.

You can apply this in your Global.asax.cs:

protected void Application_BeginRequest(object sender, EventArgs e){    HttpContextWrapper context = new HttpContextWrapper(this.Context);    if (context.Request.IsAjaxRequest())    {        context.Response.SuppressFormsAuthenticationRedirect = true;    }}


When I have FormsAuthentication in place, I will include the Login URL in the answer https://stackoverflow.com/a/3431350/1559213 provided by @Chris Kooken

protected void Application_EndRequest()    {        var context = new HttpContextWrapper(Context);        // If we're an ajax request, and doing a 302, then we actually need to do a 401        if (Context.Response.StatusCode == 302 && context.Request.IsAjaxRequest() &&             Context.Response.RedirectLocation.Contains(FormsAuthentication.LoginUrl))        {            Context.Response.Clear();            Context.Response.StatusCode = 401;        }    }