Search code examples
jqueryasp.net-mvcajaxsessionforms-authentication

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


I have some AJAX calls that render PartialViewResults via the jQuery.AJAX method. This works great, I get my views rendered exactly the way I want.

The problem arises when I leave the page up for a while and the Forms auth session expires. When I click an action that performs an AJAX request, it shows the login page in my div.

I want it to redirect the WHOLE page to the login page.


Solution

  • 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
     });