ASP.NET ActionResult 对本地主机和托管的 Azure Web 服务给出不同的响应

ASP.NET ActionResult gives different responses for localhost and Azure web service hosted

我有以下代码

public ActionResult PerformMagic(string a, string b, int c)
{
    try
    {
        // Some code which always gives an error and go to catch block
    }
    catch (Exception ex)
    {
        // ex.Message = "An error occured"

        Response.StatusCode = (int)HttpStatusCode.BadRequest;
        return this.Content(System.Web.Helpers.Json.Encode(new { error = ex.Message }), "application/json");
    }
}

所以调用 returns 下面的结果,

{
    config : {method: "GET", transformRequest: Array(1), transformResponse: Array(1), jsonpCallbackParam: "callback", paramSerializer: ƒ, …}
    data : 
        error : "An error occured"
    __proto__ : Object
    headers : ƒ (name)
    status : 400
    statusText : ""
    __proto__ : Object
}

因此,我在 JSON 中找到 data,查找 error 并将值(即 An error occured)显示为警报。

这在 运行 在本地主机上运行完美,但是当将其部署到 Azure 应用程序服务和 运行 时,响应如下

{
    config : {method: "GET", transformRequest: Array(1), transformResponse: Array(1), jsonpCallbackParam: "callback", paramSerializer: ƒ, …}
    data : "Bad Request"
    headers : ƒ (name)
    status : 400
    statusText : "Bad Request"
    __proto__ : Object
}

也就是说,我在data里面找不到error。谁能解释一下为什么会这样?

确保两台机器(localhost 和 azure)运行 是同一个 .NET Framework。否则检查处理序列化的 NuGet 包中的任何奇怪缓存。

原来,原因在于httpErrors element。与本地计算机上的行为相比,我可以想象这个元素在 Azure 上具有不同的默认行为。

长话短说:您可以通过在 web.config 中的 system.WebServer 元素下添加它来解决它:

<httpErrors existingResponse="PassThrough" />

可能的值为自动 (0)、替换 (1) 和直通 (2):

我不完全确定此更改的安全影响。但是,它确实使您能够 return(例外)向可能不属于那里的用户提供详细信息。

答案基于此post: