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?
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 = "..." } );
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With