1

Other questions similar have been asked, but they didnt tend to deal with a generic multi purpose solution. They tended to deal only with user authentication issues. Sometimes a 302 is valid for other circumstances.

So how can you create a generic 302 handler for ajax requests, while maintaining functionality for anything else in your application?

Chris
  • 165
  • 1
  • 13

2 Answers2

1

The solution we came up with in the end was a little hacky but seems quite elegant.

Start by intercepting any 302's that come from an ajax query in your global.asax file.

protected void Application_EndRequest()
{
    var context = new HttpContextWrapper(Context);
if (Context.Response.StatusCode == 302 && context.Request.IsAjaxRequest())
    {
        Context.Response.Clear();
        Context.Response.StatusCode = 308;
    }
}

We invented a status code of 308, so that the browser doesn't intercept the 302 and cause jquery to fail.

And then somewhere in your javascript global file, add the following

$(document).ajaxError(function (e, request, errorThrown, exception) {
    if (request.status == "308") {
        window.location = request.getResponseHeader('location');
    }
});

This causes jquery to be able to detect the redirect, and then direct the user to the requested page.

Chris
  • 165
  • 1
  • 13
0

It seems you can just add a conditional to check for that specific status. If request is your XMLHttpRequest object, then additionally check status when readyState is 4:

if(request.readyState == 4){
  if(request.status == 302) {
    doSomething();
  }
  else {
    doSomethingElse();
  }
}

edit:

or, alternately, if you don't want to use straight javascript (since in fairness you did tag it as jquery-ajax), then something like this:

$.ajax({
  statusCode: {
    302: function() {
      doSomething();
    }
  }
});
kinakuta
  • 9,029
  • 1
  • 39
  • 48
  • 1
    There does seem to be an issue with that solution, at least as far as I have checked, because the 302 is handled by the browser, by the time jquery gets the status code, its not actually a 302, but is set at 0 – Chris Jun 12 '11 at 21:25
  • Maybe reading this will help then: http://stackoverflow.com/questions/373087/catching-302-found-in-javascript – kinakuta Jun 12 '11 at 21:41
  • You can't catch a 302 using `statusCode`. It's handled by the browser's JavaScript engine before jQuery gets to it, so you end up with a 200 (or whatever) and the response of the redirect. – RJ Cuthbertson Jul 05 '16 at 14:20