I was trying to authorize ajax action methods in my MVC3 application. The problem occurs when the user session expires and an ajax action method is asked to execute. The asp.net Authentication system sends 302 redirect instead of sending 401 which seems logical for non-ajax requests. But with Ajax it all gets messed up quickly. So I decided to follow the approach suggested at ASP.NET MVC forces an AJAX request be redirected to the login page when the FormsLogin session is no longer active . Basically, at the end of request we check whether the request is an ajax request and there is a redirect (302 response). If it is then we replace the response code from 302 to 401. Accordingly in the javascript we check for 401 and perform redirection from there. Here is the basic code that I have put up
In Global.asax.cs
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;
}
}
In JQuery global error handler (included in asp.net mvc master page : _Layout.cshtml)
$(document).ajaxError(function (event, jqXHR, ajaxSettings, thrownError) {
if (jqXHR.status == 401) {
window.location.replace(loginUrl);
}
});
I have just quickly tested this code and it seems to work fine. Is there any potential problem with this code. I am a relatively novice programmer as far as asp.net mvc and jquery are concerned, so I thought I would ask for other opinions before actually implementing the code.