调试 400 Bad Request 响应

Debugging 400 Bad Request response

在我的 MVC 应用程序中,当 POST 请求发送到服务器(通过 jQuery)并发生验证错误时,按预期返回 400 Bad Request:

HTTP/1.1 400 Bad Request
Cache-Control: private
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/8.5
X-AspNet-Version: 4.0.30319
Date: Thu, 26 Feb 2015 08:35:50 GMT
Content-Length: 174

{"ReturnValue":null,"Results":[{"Message":"The xyz field is required.","ErrorNumber":123,"Severity":1}]}

这在我的本地机器上按预期工作。但是,当我将应用程序部署到服务器时,完全相同的请求的响应看起来不同:

HTTP/1.1 400 Bad Request
Cache-Control: private
Content-Type: text/html
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
Date: Thu, 26 Feb 2015 08:37:01 GMT
Content-Length: 24

Invalid Request

请注意,内容类型为 text/html,响应正文不再包含 JSON。

这可能是什么原因造成的?我将不胜感激从哪里开始调试的指示。

经过进一步搜索和阅读,我在 this post which also refers to the helpful article IIS 7 Error Pages taking over 500 Errors

中找到了答案

问题是 IIS 接管了 400 多个错误请求错误并用 IIS 错误内容替换了我的自定义 JSON 响应。可以使用 TrySkipIisCustomErrors 设置禁用此行为:

Response.TrySkipIisCustomErrors = true;
Response.StatusCode = 400;