[英]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.