401 response code for json requests with ASP.NET MVC

In classic ASP.NET you get a 401 http response code when calling a WebMethod with Ajax. I hope they’ll change it in future versions of ASP.NET MVC. Right now I’m using this hack:

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

Leave a Comment