我在向 ajax 调用发送自定义错误消息时遇到问题。我的 Controller 返回如下内容:
return new HttpStatusCodeResult(400, "My error!");
我的 ajax 代码如下所示:
error: function (xhr, httpStatusMessage) {
console.log(xhr.statusText);
console.log(httpStatusMessage);
}
问题是 xhr.statusCode 和 httpStatusMessage 总是“错误”。我现在做错了什么? 我期待着“我的错误!”在 xhr.statusText 中。
我正在使用 ASP.NET MVC 5
和 jquery-1.10.2
我的 xhr 输出是:
abort:ƒ ( statusText )
always:ƒ ()
complete:ƒ ()
done:ƒ ()
error:ƒ ()
fail:ƒ ()
getAllResponseHeaders:ƒ ()
getResponseHeader:ƒ ( key )
overrideMimeType:ƒ ( type )
pipe:ƒ ( /* fnDone, fnFail, fnProgress */ )
progress:ƒ ()
promise:ƒ ( obj )
readyState:4
responseText:"Bad Request"
setRequestHeader:ƒ ( name, value )
state:ƒ ()
status:400
statusCode:ƒ ( map )
statusText:"error"
success:ƒ ()
then:ƒ ( /* fnDone, fnFail, fnProgress */ )
我的 Web.config httpErrors 配置如下所示:
<httpErrors existingResponse="PassThrough" errorMode="Custom">
<remove statusCode="404" />
<error statusCode="404" path="/Error/NotFound" responseMode="ExecuteURL" />
<remove statusCode="403" />
<error statusCode="403" path="/Error/Forbidden" responseMode="ExecuteURL" />
</httpErrors>
而且,在我的开发环境中,responseText 是空的,而 statusText 只是“错误”。
最佳答案
您需要在 Web.Config 文件中设置一个属性。
引用 this web page 的用户在 github 上,强调我的,
By default IIS will mask your error codes and replace them with default errors. The "PassThrough" option tells IIS to leave your custom errors alone and render them as-is.
“错误请求”是默认值 http error text对于状态码 400。
所以设置为documented here和 outlined here ,
<configuration>
<system.webServer>
<httpErrors existingResponse="PassThrough"></httpErrors>
</system.webServer>
</configuration>
请仔细查阅您的 IIS 版本的文档,其中存在许多细微的版本差异。
编辑
不是真正特定于 MVC,但这是我曾经解决它的方式(生产代码的一部分),似乎也对 OP 有帮助:
Response.TrySkipIisCustomErrors = true;
Response.StatusCode = (int)HttpStatusCode.InternalServerError;
Response.ContentType = "text/plain";
Response.Write(new String('_', 513) + "my custom message");
这absurd minimum character limit thing可能需要也可能不需要,具体取决于 IIS 版本。如果有人能进一步说明这种未被记录的行为,我将不胜感激。
关于javascript - ASP.NET MVC 5 ajax 错误 statusText 始终为 "error",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48096060/