[英]Return individual error message after an ajax call in ASP.NET MVC 5
當我向服務器發送 ajax 請求時,我想在 responseText 中向客戶端返回一條單獨的消息,以防出錯。 在我的開發機器上的調試模式下,這工作正常。 不幸的是,在 web 服務器的生產模式下,我總是收到錯誤消息“錯誤請求”,但不再是單個消息。 我正在 ASP.NET MVC 5 中開發我的應用程序,我正在使用 jQuery 3.6.0。
我的 ajax 請求如下所示:
$.ajax({
type: 'POST',
url: 'myURL',
data: {
val1: clientVal1,
val2: clientVal2
},
success: function (res) {
//do smthg...
},
error: function (response) {
alert(response.responseText);
}
});
在服務器端,我使用 ajax 調用如下:
[HttpPost]
public ActionResult myURL(string val1, string val2)
{
if(val1.contains(val2))
{
}
else
{
Response.StatusCode = 400;
Response.Write("My custom error msg.");
return new HttpStatusCodeResult(400);
}
return Json(new { someVal1, otherVal2}, JsonRequestBehavior.AllowGet);
}
我的 webconfig 文件中的 httperrors 如下所示:
<httpErrors errorMode="Custom" existingResponse="Replace">
<remove statusCode="404" subStatusCode="-1" />
<remove statusCode="403" subStatusCode="-1" />
<remove statusCode="500" subStatusCode="-1" />
<error statusCode="404" path="/ErrorHandling/http404" responseMode="ExecuteURL" />
<error statusCode="403" path="/ErrorHandling/http403" responseMode="ExecuteURL" />
<error statusCode="500" path="/ErrorHandling/http500" responseMode="ExecuteURL" />
</httpErrors>
我究竟做錯了什么?
我找到了解決方案。 首先,我必須將重定向到 web.config 中的各個錯誤頁面移動到 <system.web> 區域。 現在我的 system.web 區域看起來像這樣([...] 表示還有其他與此無關的設置):
<system.web>
[...]
<customErrors mode="On" redirectMode="ResponseRedirect" defaultRedirect="/ErrorHandling/http500">
<error statusCode="404" redirect="/ErrorHandling/http404" />
<error statusCode="403" redirect="/ErrorHandling/http403" />
<error statusCode="500" redirect="/ErrorHandling/http500" />
</customErrors>
[...]
</system.web>
之后,我不得不按照 freen-m 的帖子中的建議和 Rahul Sharam 的建議更改 system.webServer 部分,如下所示:
<httpErrors errorMode="Custom" existingResponse="PassThrough">
</httpErrors>
現在一切正常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.