Take the 2-minute tour ×

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.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) {

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.

share|improve this question
add comment

1 Answer

up vote 4 down vote accepted

Here's a blog post which I would strongly recommend you reading. It illustrates a better approach for handling this.

share|improve this answer
Thanks for the link. I think I will go with the approach suggested in the blog. I installed the Nuget package for the same and it seems to work fine. –  Nirvan Nov 2 '11 at 22:22
@Nirvan, great. I am happy you have adopted this approach. –  Darin Dimitrov Nov 2 '11 at 22:25
add comment

Your Answer


