ASP.NET MVC 5 ajax 错误状态文本始终为“错误”

2023-12-08

我在向 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 and 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 保留您的自定义错误并按原样呈现它们。

默认为“错误请求”http 错误文本状态代码 400。

所以有这样的设置记录在这里 and 此处概述,

<configuration>
  <system.webServer>
    <httpErrors existingResponse="PassThrough"></httpErrors>
  </system.webServer>
</configuration>

请仔细查阅您的 IIS 版本的文档,其中存在许多细微的版本差异。

EDIT

并不是 MVC 特有的,但这是我曾经解决它的方法(生产代码的一部分),并且似乎也对 OP 有帮助:

Response.TrySkipIisCustomErrors = true;
Response.StatusCode = (int)HttpStatusCode.InternalServerError;
Response.ContentType = "text/plain";
Response.Write(new String('_', 513) + "my custom message");

This 荒谬的最小字符限制可能需要也可能不需要,具体取决于 IIS 版本。如果有人能够对这种未记录的行为有更多的了解,我也将不胜感激。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ASP.NET MVC 5 ajax 错误状态文本始终为“错误” 的相关文章