【问题标题】:ASP.NET: Webmethos does not return payload when http status is 4xxASP.NET:当 http 状态为 4xx 时,Webmethos 不返回有效负载
【发布时间】:2018-10-15 15:42:14
【问题描述】:

我有以下代码:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static MyResponse myMethod(ParameterClass parameters)
{
    MyResponse resp = new MyResponse();
    resp.errors.Add("Some error message");
    HttpContext.Current.Response.StatusCode = 400;
    return resp;
}

使用 jQuery.ajax 使用 url MyPage.aspx/myMethod 运行此调用不会从 MyResponse 对象返回我的有效负载。一旦我将状态码切换到 200,返回工作使用 ajax 中的成功回调,但我想返回带有 4xx 和 5xx 状态码的自定义错误消息,如何使其工作。

看起来 IIS 是问题所在,但我必须做些什么才能仍然允许在错误时返回我的类对象?

更新 1: 我也在 chrome 中查看了网络选项卡,IIS 根本没有返回有效负载,所以 jQuery 不是问题。

更新 2:我的 jquery ajax 调用

$.ajax({
  url: 'MyPage.aspx/myMethod',
  data: JSON.stringify({ parameters: request }),
  dataType: "json",
  type: "POST",
  contentType: "application/json; charset=utf-8",
  success: function (data) {
    ...
  },
  error: function (data) {
    // data.responseJSON is undefined and data.responseText contains only HTTP status code text, like "Bad Request" when code was 400.
  }
});

【问题讨论】:

  • 不只是jquery因为不是200才调用你的success方法的情况吗?

标签: c# asp.net webmethod


【解决方案1】:

好的,在另一个 stackoverflow 帖子中找到它。

解决方案是在 web.config 中添加以下内容:

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

默认情况下,IIS 会替换错误响应,这里的属性“existingResponse=PassThrough”是关键。现在 responseJSON 和 responseText 填充了我的 webmethod 返回的自定义内容。

发现于HttpResponseMessage content lost when HTTP Status is Bad Request

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-31
    • 2017-10-22
    • 1970-01-01
    • 2018-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多