javascript - ASP.NET MVC 5 ajax 错误 statusText 始终为 "error"

标签 javascript jquery asp.net ajax asp.net-mvc

我在向 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 5jquery-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 hereoutlined 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/

相关文章:

javascript - 如何从 polymer 纸菜单中删除菜单选项

javascript - 为什么 javascript 将 typeof 显示为 "string"当它是数字时?

c# - 有没有办法在 ASP.NET/C# 中不加载特定控件?

c# - 如何在 Visual C# 中从 Active Directory 填充 gridview

c# - 如何匹配并返回字符串的多个实例,其中任何索引中都可以包含单个撇号?

c# - 使用 ManagementScope (WMI) - 有什么问题吗?

javascript - 如何使用变量字段名增加mongodb字段?

javascript - NodeJS 模块化

javascript - Jest/eslint 中函数缺少返回类型

jquery - 如何将 textbox1 的值传输到 textbox2 中,每个输入以逗号分隔