簡體   English   中英

ASP.NET MVC 5 Ajax錯誤statusText始終為“錯誤”

[英]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 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文件中設置一個屬性。

在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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM