Return 在 ASP.NET MVC 5 中调用 ajax 后的个别错误消息

Return individual error message after an ajax call in ASP.NET MVC 5

当我向服务器发送 ajax 请求时,我想 return 在 responseText 中向客户端发送一条单独的消息以防出现错误。在我的开发机器上的调试模式下,这工作正常。不幸的是,在 Web 服务器的生产模式下,我总是收到错误消息“Bad Request”,但不再是单独的消息。我正在 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>
    [...]
    <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>

之后,我不得不按照 freeden-m post 中的建议和 Rahul Sharam 的建议更改 system.web 服务器部分,如下所示:

<httpErrors errorMode="Custom" existingResponse="PassThrough">
</httpErrors>

现在一切正常。