ASP.NET ActionResult gives different responses for

2019-07-31 06:26发布

问题:

I have the following code

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

So the call returns the below result,

{
    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
}

So, I get the data inside the JSON, look for error and display the value (which is An error occured) as an alert.

This works perfectly when running in localhost, but when deploy this to Azure App service and run, the response comes as below

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

That means, I cant find error inside data. Can anyone explain me why this behaves like this?

回答1:

As it turns out, the cause of this lies in the httpErrors element. I can imaging this element having different default behavior on Azure compared to the behavior on a local machine.

Long story short: you can solve it by adding this under the system.WebServer element in web.config:

<httpErrors existingResponse="PassThrough" />

Possible values are Auto (0), Replace (1) and PassThrough (2):

I'm not entirely sure about security implications of this change. It does however enable you to return (exception) details to users that might not belong there.

The answer is based on this post: ASP.NET+Azure 400 Bad Request doesn't return JSON data



回答2:

Make sure both machines (localhost and azure) are running the same .NET Framework. Otherwise check any weird caching within your NuGet packages that handle the serialization.