[英]ASP.NET MVC 5 ajax error statusText is always “error”
我在将错误的自定义消息发送到ajax调用时遇到问题。 我的控制器返回如下内容:
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文件中设置一个属性。
在github上引用此网页的用户,重点是我的,
默认情况下,IIS将屏蔽您的错误代码并将其替换为默认错误 。 “ PassThrough”选项告诉IIS保留您的自定义错误,并按原样呈现它们。
“错误请求”是状态码400的默认http错误文本 。
<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");
根据IIS版本的不同,可能需要或可能不需要此荒谬的最小字符限制 。 如果有人能进一步阐明这种证据不足的行为,我也将不胜感激。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.