ASP.NET MVC 5 ajax 错误 statusText 总是“错误”

Rob*_*ert 2 javascript asp.net ajax asp.net-mvc jquery

我在向 ajax 调用发送错误的自定义消息时遇到问题。我的控制器返回如下内容:

return new HttpStatusCodeResult(400, "My error!");
Run Code Online (Sandbox Code Playgroud)

我的 ajax 代码如下所示:

error: function (xhr, httpStatusMessage) {
              console.log(xhr.statusText);
              console.log(httpStatusMessage);
}
Run Code Online (Sandbox Code Playgroud)

问题是 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 */ )
Run Code Online (Sandbox Code Playgroud)

我的 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>
Run Code Online (Sandbox Code Playgroud)

而且,在我的开发环境中,responseText 是空的,statusText 只是“错误”。

Cee*_* it 5

您需要在 Web.Config 文件中设置一个属性。

在 github 上引用这个网页的用户,强调我的,

默认情况下 IIS 将屏蔽您的错误代码并用默认错误替换它们。“PassThrough”选项告诉 IIS 不理会您的自定义错误并按原样呈现它们。

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

因此,此处记录概述了此处的设置,

<configuration>
  <system.webServer>
    <httpErrors existingResponse="PassThrough"></httpErrors>
  </system.webServer>
</configuration>
Run Code Online (Sandbox Code Playgroud)

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

编辑

并非真正特定于 MVC,但这是我曾经解决它的方式(生产代码的一部分),以及似乎对 OP 也有帮助的方法:

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

根据 IIS 版本,可能需要也可能不需要这种荒谬的最小字符限制。如果有人能对这种记录不足的行为有更多的了解,我也将不胜感激。

  • 在控制器中使用以下代码编写响应:Response.TrySkipIisCustomErrors = true; Response.StatusCode = (int)HttpStatusCode.BadRequest; 返回内容(“消息”);这就是我让它工作的方式,它基于你的帮助。 (2认同)