Pri*_*cey 0 javascript ajax jquery json asp.net-mvc-4
我有以下示例代码,它在我的本地开发环境中工作,但是当发布到使用HTTPS的实时环境并使用.NET捆绑用于javascript和ELMAH用于错误记录时,这不再按预期工作.
我得到的是一个带有responseText"错误请求" 的HTML内容响应而没有responseJSON属性,而不是JSON内容响应,所以这段代码会导致javascript错误.
有谁知道为什么内容类型会改变?大概是因为这是在一个现场环境和响应代码400?但我不确定这里发生了什么.
控制器:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
使用Javascript:
$.ajax("/Controller/GetData/", {
dataType: "json",
type: "POST",
contentType: "application/json"
})
.done((result) => {
})
.fail((xhr) => {
setTimeout(() => {
this.errors(xhr.responseJSON);
}, 200);
})
.always(() => {
});
Run Code Online (Sandbox Code Playgroud)
更新:
当我在Chrome中查看请求的响应时,这是响应标头:
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
Run Code Online (Sandbox Code Playgroud)
并且来自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>
Run Code Online (Sandbox Code Playgroud)
在测试时我将模式更改为"关闭",但这在IIS8的实时环境中不起作用,也许我错过了需要更新的内容才能使IIS正确执行此操作或者defaultRedirect="~/Error">应该已将其删除?但是将该行添加
Response.TrySkipIisCustomErrors = true;
到JsonModelErrorResult代码中已停止此内容/ html错误,并返回"Bad Request"行.
在您设置Response.StatusCode添加此行代码后:
Response.TrySkipIisCustomErrors = true;
Run Code Online (Sandbox Code Playgroud)
这告诉IIS不要拦截请求并使用自己的错误页面.
| 归档时间: |
|
| 查看次数: |
1622 次 |
| 最近记录: |