ASP.NET MVC returning 302 (Found) HTTP status code on unauthorized Ajax calls instead of 401(Unauthorized) like classic ASP.NET

Classic ASP.NET

On classic ASP.NET when calling a [WebMethod] with Ajax in an unauthorized context (most likely in the case where the session expired) the response http status code is 401. You can handle this in the “error” handler (provided by most Ajax frameworks) and redirect to login page. For example I use this code with jQuery:


public static MyModel GetStuff()
    return new MyModel();


    type: "POST",
    url: "Default.aspx/GetStuff",
    data: "{}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
        // do stuff
    error: function(xhr, status, ex) {
        if (xhr.status == 401) // unauthorized
            window.location = "Login.aspx?ReturnUrl=" + window.location.pathname;


To do the same in ASP.NET MVC I have this method in my controller:

public ActionResult GetStuff()
    return Json(new MyModel());

The ASP.NET MVC infrastructure doesn’t return 401 http status code on failed authorization but 302 http status code (actually the 401 status code is returned initially but later, in the same request, is intercepted by the infrastructure and replaced by 302 status code). XMLHttpRequest object handles this internally automatically following the redirect (no event is fired client side). The Ajax call will end in “success” but the message won’t be the expected JSON but the html of the login page.

The best (well, it’s a hack, if you a better way please tell me) way I found is to replace 302 status code by 401 status code on request end. I added the following code to Global.asax :

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

And the client side code (using Ext JS this time) is:

Ext.Ajax.on('requestexception', function(conn, response, options) {
    if (response.status == 401) {
        window.location = '<%= Html.ActionUrl("Account", "LogOn") %>?ReturnUrl=' +
This entry was posted in AJAX, JavaScript. Bookmark the permalink.

28 Responses to ASP.NET MVC returning 302 (Found) HTTP status code on unauthorized Ajax calls instead of 401(Unauthorized) like classic ASP.NET

  1. Josh says:

    Funny, I am having this same issue, in a custom handler I am working on. Your solution won’t work in my case as sometimes we will want the 302 error for other paths in the application.

  2. Brian says:

    Hi Ben,

    Thanks for posting this up, I am currently trying to implement an MVC uploader and this post is a helpful starting point. One problem I am having with your code is that Im getting a 302 HTTP error every time I post to my controler. Any ideas on why this should be?

    Thanks again,


  3. Brian says:

    Sorry … posted to wrong blog :(

  4. Heya i’m for the first time here. I found this board and I find It truly helpful & it
    helped me out much. I’m hoping to present one thing again and help others
    such as you helped me.

  5. meble oferta says:

    konnicy zaś pewność na rowerze ,maluch przypadkiem mieć chęć tyłek zmniejszone w ten sposób, że jej raty płasko na ziemi, kiedy.

  6. rea says:

    Heya i am for the primary time here. I found this board and I find It
    really helpful & it helped me out a lot. I hope to progide
    one thing back and aaid others like you helped me.

  7. Com|squidoo|youtube|bebo|flickr|hub pages|wikipedia|tagged|facebook game|social networks|the facebook|online social networks|facebook itself} top dog grade Zuckerberg eat pledged to utilize in keeping with the ‘No Ad’ regulation. in fact, according to designer and magnificence mavens, Another awesome thing about almost all of these boots is they make our leg overall look thin together with well developed.
    cheap retro jordans

  8. Birgit says:

    I see you share interesting content here, you can earn some extra money, your website has big
    potential, for the monetizing method, just type in google – K2
    advices how to monetize a website

  9. Agueda says:

    I read a lot of interesting articles here.
    Probably you spend a lot of time writing, i know how to save you
    a lot of time, there is an online tool that creates unique, SEO friendly posts in minutes,
    just search in google – laranitas free content source

  10. Corrine says:

    Every weekend i used to pay a quick visit this web site,
    as i wish for enjoyment, since this this site conations in fact good funny stuff too.

  11. My Rank says:

    Nice article 838, I fell the same way about Dotnet as this guy explained on TED

  12. 即日融資 says:


  13. Gregorio1979 says:

    Hello blogger, do you monetize your site ?
    There is easy method to earn extra money every day, just search on youtube : How to earn with wordai 4

  14. If you want to get more visitors to, you should really check out this free training:

  15. FirstJavier says:

    I see you don’t monetize your site, don’t waste your
    traffic, you can earn extra cash every month because you’ve got high quality content.
    If you want to know how to make extra $$$, search for:
    Boorfe’s tips best adsense alternative

  16. Asѕim você tem como ganhar dinheiro nas redes sociais.

  17. Everett says:

    Hey there, You’ve done a great job. I will certainly digg it
    and personally recommend to my friends. I’m confident they’ll be benefited from this web site.

  18. thaitrade scam bangkok tuk tuk scam bangkok bar scam gem scam thailand
    thailand hospital scam

  19. Zapraszam na mojego bloga KatKatMatura0098. Zdjęcia, artykuły…

  20. Ewelina says:

    Zapraszamy po przykładowe biznes plany. Dziesiątki przykładów i pomysłów na biznes.

  21. Maybell Fielding says:

    Hello there!

    You Need Leads, Sales, Conversions, Traffic for ? Will Findet…


    Don’t believe me? Since you’re reading this message then you’re living proof that contact form advertising works!
    We can send your ad to people via their Website Contact Form.

    IF YOU ARE INTERESTED, Contact us =>


  22. Zajrzyj na mojego osobistego bloga KatKatMatura0098. Fotosy, artykuły…

  23. Leola York says:


    I will Find Leads that Buy From You
    I will Promote Your Business In Any Country To Any Niche.


  24. Bryant Rigg says:

    Good day

    I just checked out your website and wanted to find out if you need help for SEO Link Building ?

    If you aren’t using SEO Software then you will know the amount of work load involved in creating accounts, confirming emails and submitting your contents to thousands of websites.

    With THIS SOFTWARE the link submission process will be the easiest task and completely automated, you will be able to build unlimited number of links and increase traffic to your websites which will lead to a higher number of customers and much more sales for you.

    IF YOU ARE INTERESTED, We offer you 7 days free trial

    Kind Regards,
    Bryant Rigg ! Business Development Manager

  25. Diriam says:

    Zapraszam wszystkich do odwiedzenia mojej nowej strony Znajdziecie tam artykuły z tematyki biznesowej, ekonomicznej, marketingowej….

  26. Bernardo Bivens says:


    I’m talking about a better promotion method than all that exists on the market right now, even better than email marketing.
    Just like you received this message from me, this is exactly how you can promote your business or product.

    CLAIM YOUR FREE TEST (Contact me)
    Skype ID : (live:.cid.5554a4758747b4a5)
    Email: (

  27. Evela says:

    Great post. It’s good that you bring up this topic. It will be useful for a lecture to high school. Thanks! ps. I invite you to visit my website Articles are in Polish, but maybe there is someone who understands this language :-)

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>