Skip to main content
 首页 » 编程设计

c#之ASP.NET ActionResult 为本地主机和托管的 Azure Web 服务提供不同的响应

2024年02月27日36del

我有以下代码

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"); 
    } 
} 

因此调用返回以下结果,

{ 
    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 occurred)显示为警报。

这在本地主机上运行时完美运行,但当将其部署到 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。谁能解释一下为什么会这样?

请您参考如下方法:

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

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

<httpErrors existingResponse="PassThrough" /> 

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

我不完全确定此更改的安全影响。但是,它确实使您能够将(异常)详细信息返回给可能不属于那里的用户。

答案基于这篇文章:ASP.NET+Azure 400 Bad Request doesn't return JSON data