我有下面的示例代码,可以在我的本地开发环境中运行,但是当发布到使用 HTTPS 并使用 .NET 捆绑 JavaScript 和 ELMAH 进行错误记录的实时环境时,这不再按预期运行。
我得到的不是 JSON 内容响应,而是带有 responseText
“错误请求”的 HTML 内容响应,并且没有 responseJSON
属性,因此此代码会导致 JavaScript 错误。
有谁知道为什么内容类型会改变?大概是因为这是在实时环境中并且响应代码为 400?但我不确定这里发生了什么。
Controller :
public JsonResult JsonModelErrorResult()
{
Response.StatusCode = 400;
var errors = ModelState.Values.SelectMany(m => m.Errors);
return Json(errors);
}
[HttpPost]
public ActionResult GetData()
{
...
if (results != null && results.Any())
{
return Json(result, JsonRequestBehavior.AllowGet);
}
else
{
ModelState.AddModelError("SearchResults", "No results found");
return this.JsonModelErrorResult();
}
}
Javascript:
$.ajax("/Controller/GetData/", {
dataType: "json",
type: "POST",
contentType: "application/json"
})
.done((result) => {
})
.fail((xhr) => {
setTimeout(() => {
this.errors(xhr.responseJSON);
}, 200);
})
.always(() => {
});
<小时/>
更新:
这是我在 Chrome 中查看请求响应时的响应 header :
HTTP/1.1 400 Bad Request
Cache-Control: no-cache, no-store, must-revalidate
Pragma: no-cache
Content-Type: text/html
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNetMvc-Version: 4.0
X-AspNet-Version: 4.0.30319
Persistent-Auth: true
X-Powered-By: ASP.NET
Date: Thu, 03 Jul 2014 12:08:23 GMT
Content-Length: 11
ajax 调用的返回值是一个 Jquery jqXHR 对象,其 responseText
属性为 "Bad Request"
,内容类型为 "text/html”
更新2: 这是我的 web.config 中的自定义错误设置
<customErrors mode="RemoteOnly" defaultRedirect="~/Error">
<error statusCode="401" redirect="~/Error/NotAuthorised" />
<error statusCode="403" redirect="~/Error/NotAuthorised" />
<error statusCode="404" redirect="~/Error/NotFound" />
</customErrors>
在测试时,我将模式更改为“关闭”,但这在 IIS8 的实时环境中不起作用,也许我错过了一些需要更新的内容,以便 IIS 正确执行此操作,或者 defaultRedirect ="~/Error">
也应该被删除吗?
但添加行
Response.TrySkipIisCustomErrors = true;
进入 JsonModelErrorResult 代码已停止此 content/html 错误,并返回“Bad Request”行。
最佳答案
设置Response.StatusCode
后立即添加以下代码行:
Response.TrySkipIisCustomErrors = true;
这告诉 IIS 不要拦截请求并使用它自己的错误页面。
关于javascript - 带有 json 内容类型的 jquery ajax post 以 HTML 形式返回错误请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24520780/