ASP.NET ActionResult对托管的localhost和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");
}
}
因此该调用返回了以下结果,
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
}
因此,我在JSON中获取了data
,查找error
并显示该值(即An error occured
)作为警报.
So, I get the data
inside the JSON, look for error
and display the value (which is An error occured
) as an alert.
这在localhost中运行时效果很好,但是将其部署到Azure App服务并运行时,响应如下所示
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
}
这意味着,我在data
内找不到error
.谁能解释我为什么会这样?
That means, I cant find error
inside data
. Can anyone explain me why this behaves like this?
推荐答案
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.
长话短说:您可以通过在web.config的system.WebServer
元素下添加此内容来解决此问题:
Long story short: you can solve it by adding this under the system.WebServer
element in web.config:
<httpErrors existingResponse="PassThrough" />
可能的值为自动"(0),替换"(1)和通过"(2):
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.
答案基于以下帖子: ASP.NET + Azure 400错误请求不会返回JSON数据
这篇关于ASP.NET ActionResult对托管的localhost和Azure Web服务给出不同的响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!