Rex T
Rex T

Reputation: 77

Controller JsonResult method always return status code 200 (OK)

I have a code block like this:

public class AccountController : Controller
{
    [HttpPost]
    public JsonResult Check(LoginModel model){
        ...
        Response.StatusCode = (int)HttpStatusCode.Unauthorized;
        return Json( new { ErrorMessage = "..." } );
    }
}

This logic I want to send status code 401 back to the client.

In my frontend, I use the jquery ajax method to call this method.

$.ajax({
  ...
  success: function(data, textStatus, xhr){
  ...
  },
  error: function(xhr, textStatus, error){
  ...
  }
});

However, the error callback can never be reached.

I used postman to debug, and I found that no matter what I always receive 200(OK).

Do you guys have any idea what's going on here?

Upvotes: 3

Views: 4316

Answers (2)

synus_wroc
synus_wroc

Reputation: 31

I have also faced this problem in my ASP.Net MVC 5 application. In my case I'm using OWIN middleware with ASP.Net Identity v 2.0 in order to authenticate user. Strangely the default behaviour of the Katana project is to override HTTP code from 401 to 200 and putting your original code of 401 with related message to header called

*X-Responded-JSON*, like this:
*X-Responded-JSON: {"status":401,"headers":{"location":"http:\/\/localhost:59540\/Account\/Login?ReturnUrl=%2Fapi%2FTestBasic"}}*

in order to suppress default behaviour you need to update the StartUp class. More you can find here: http://kevin-junghans.blogspot.in/2013/12/returning-401-http-status-code-on.html

which is the solution base on this post: https://brockallen.com/2013/10/27/using-cookie-authentication-middleware-with-web-api-and-401-response-codes/

Upvotes: 3

TomasF
TomasF

Reputation: 116

That is the default behavior, sadly. Whenever you get Unauthorized access (401), MVC kicks in and redirects you to login page, where your 200(OK) comes from and which is why you never get the response you want - 401. To be able to return 401 code, you have to explicitly suppress Authentication Redirect of your response like this:

HttpContext.Response.SuppressFormsAuthenticationRedirect = true;

So what you get is:

public class AccountController : Controller
{
    [HttpPost]
    public JsonResult Check(LoginModel model)
    {
        ...
        Response.StatusCode = (int)HttpStatusCode.Unauthorized;
        Response.SuppressFormsAuthenticationRedirect = true;
        return Json( new { ErrorMessage = "..." } );
    }
}

Upvotes: 5

Related Questions