Asp.net mvc 控制器JsonResult方法始终返回状态代码200(OK)
我有这样一个代码块:Asp.net mvc 控制器JsonResult方法始终返回状态代码200(OK),asp.net-mvc,asp.net-mvc-4,asp.net-ajax,Asp.net Mvc,Asp.net Mvc 4,Asp.net Ajax,我有这样一个代码块: public class AccountController : Controller { [HttpPost] public JsonResult Check(LoginModel model){ ... Response.StatusCode = (int)HttpStatusCode.Unauthorized; return Json( new { ErrorMessage = "..." } );
public class AccountController : Controller
{
[HttpPost]
public JsonResult Check(LoginModel model){
...
Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Json( new { ErrorMessage = "..." } );
}
}
HttpContext.Response.SuppressFormsAuthenticationRedirect = true;
我想将状态代码401发送回客户机
在我的前端,我使用jQueryAjax方法来调用这个方法
$.ajax({
...
success: function(data, textStatus, xhr){
...
},
error: function(xhr, textStatus, error){
...
}
});
但是,永远无法到达错误回调
我使用postman进行调试,我发现无论怎样,我总是收到200(OK)
你们知道这里发生了什么吗?很遗憾,这是默认行为。每当您获得未经授权的访问(401),MVC就会启动并将您重定向到登录页面,您的200(OK)来自该页面,这就是为什么您从未得到想要的响应-401。 为了能够返回401代码,您必须明确禁止响应的身份验证重定向,如下所示:
public class AccountController : Controller
{
[HttpPost]
public JsonResult Check(LoginModel model){
...
Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Json( new { ErrorMessage = "..." } );
}
}
HttpContext.Response.SuppressFormsAuthenticationRedirect = true;
所以你得到的是:
public class AccountController : Controller
{
[HttpPost]
public JsonResult Check(LoginModel model)
{
...
Response.StatusCode = (int)HttpStatusCode.Unauthorized;
Response.SuppressFormsAuthenticationRedirect = true;
return Json( new { ErrorMessage = "..." } );
}
}
我在ASP.NETMVC5应用程序中也遇到了这个问题。在我的例子中,我使用带有ASP.NETIdentityv2.0的OWIN中间件对用户进行身份验证。奇怪的是,Katana项目的默认行为是将HTTP代码从401覆盖到200,并将原始代码401和相关消息放入名为
*X-Responded-JSON*, like this:
*X-Responded-JSON: {"status":401,"headers":{"location":"http:\/\/localhost:59540\/Account\/Login?ReturnUrl=%2Fapi%2FTestBasic"}}*
为了抑制默认行为,您需要更新StartUp类。您可以在这里找到更多信息:
这篇文章的解决方案是什么: