ASP.NET MVC 5 JsonResult 不包含非 Http.OK 响应的负载

ASP.NET MVC 5 JsonResult does not include payload for non-Http.OK responses

我正在从 AngularJs 发送 GET 请求,我想在失败时显示实际的服务器错误(这是一个概念验证,因此我可以向测试人员显示技术错误)。这在本地主机上工作正常,但对于远程请求失败(当部署在服务器上时)。

注意:为了更好的可读性,不相关的代码被删除了

客户代码

$http(loadReqData).success(function(data, status ) {
    if (status !== 200) {
        // non OK responses handling ...
        return;
    }

    // ok handling
}).error(function(data, status, headers, config) {
    // error handling ...
    // here I do not receive expected information (in data variable)
}).finally(function() {
    $loading.finish(loaderName);
});

服务器端

这是一个 MVC 控制器,而不是 Web.API 一个

[Route("GetEnvironmentTableRowCount")]
public JsonResult GetEnvironmentTableRowCount(int environmentId, string tableName, string whereClause)
{
    try
    {
        long? rowCount = TeradataUtilsService.GetRowCount(environmentId, tableName, whereClause);
        return Json(new { RowCount = rowCount }, JsonRequestBehavior.AllowGet);
    }
    catch (Exception exc)
    {
        Logger.Log(LogLevel.Error, exc, "Failed to get row count");
        Response.StatusCode = (int)HttpStatusCode.BadRequest;
        return Json($"Failed to get row count - {exc.Message}", JsonRequestBehavior.AllowGet);
    }
}

当 运行 在本地主机上出现错误时 data 将收到实际错误:

Failed to get row count - ...

当服务器上 运行 出现错误时 data 将仅包含

Bad request

我已允许显示自定义错误 (web.config):

<system.web>      
    <customErrors mode="Off" />       
</system.web>  

问题:为什么部署在服务器上收不到http响应内容?

请尝试将此添加到您的 web.config:

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

请注意,这将适用于 所有 错误响应,但您应该通过设置 Response.Code 来达到预期的结果自定义响应。