jQuery AJAX see redirect as status 200 not 302?

Slee picture Slee · Aug 12, 2009 · Viewed 7.3k times · Source

I am using jQuery and the jQuery.form plugin to submit my form (also using ASP.Net MVC).

Problem is the user is in a section of the site that uses forms authentication and if their auth cookie expires during their time on the page instead of getting back a status of 302, which would be the redirect to the login page, I still get 200?

In FireBug I see the 302 Found and then my login page is served next as a 200 which is the status code sent back to my Ajax call. How do I detect that they have been logged out if I never see the 302 sent back to the jQuery form plugin?

Answer

user342706 picture user342706 · Jul 14, 2011

I really like this solution. By changing the 302 response on ajax requests to a 401 it allows you to setup your ajax on the client side to monitor any ajax request looking for a 401 and if it finds one to redirect to the login page. Very simple and effective.

Global.asax:

protected void Application_EndRequest()
{
    if (Context.Response.StatusCode == 302 &&
        Context.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
    {
        Context.Response.Clear();
        Context.Response.StatusCode = 401;
    }
}

Client Side Code:

 $(function () {
      $.ajaxSetup({
        statusCode: {
          401: function () {
            location.href = '/Logon.aspx?ReturnUrl=' + location.pathname;
          }
        }
      });
    });