【问题标题】:Response JSON format changing depending on success/error: why?响应 JSON 格式根据成功/错误而改变:为什么?
【发布时间】:2016-04-26 05:17:55
【问题描述】:

我正在构建一个 Web Api,使用 Ajax 调用来测试上传文件的操作。

Ajax 看起来就像这样:

$.ajax({
    type: 'POST',
    cache: false,
    contentType: false,
    processData: false,
    url: './Customer/' + self.uploadCustomer() + '/Upload',
    data: formData,
    headers: headers,
    success: function (result) {
        self.result(JSON.stringify(result));
    },
    error: function (result) {
        self.result(JSON.stringify(result));
    }
});

在我的操作中,如果出现错误,我想返回一个 JSON 自定义对象,例如:

return ResponseMessage(Request.CreateResponse(HttpStatusCode.OK, new ResultError(ErrorCode.CustomerNotFound)));

它应该返回以下内容,因为它应该

{
    "Errors": [
        {
            "Message": "Customer doesn't exist or access is forbidden.",
            "Code": 201
        }
    ]
}

但如果我不使用HttpStatusCode.OK,而是使用任何其他方法,例如HttpStatusCode.NotFound,在与我上面完全相同的调用中:

return ResponseMessage(Request.CreateResponse(HttpStatusCode.NotFound, new ResultError(ErrorCode.CustomerNotFound)));

我得到了这个结果:

{
    "readyState":4,
    "responseText":"{\"Errors\":[{\"Message\":\"Customer doesn't exist or access is forbidden.\",\"Code\":201}]}",
    "responseJSON":{"Errors":[{"Message":"Customer doesn't exist or access is forbidden.","Code":201}]},
    "status":404,
    "statusText":"Not Found"
}

为什么?我该如何摆脱它?

【问题讨论】:

  • Request.CreateResponse 就是这样工作的。如果你的 HttpStatusCode 不是 OK 它会用这个结构包装你的回复。你期望得到什么?
  • @teo van kot 正如我所说,我希望两个响应的格式相同。他们不是。 Request.CreateResponse 根据HttpStatusCode 返回不同的 JSON,我想知道 a) 为什么? b)如何改变它?。

标签: c# json ajax asp.net-web-api httpresponse


【解决方案1】:

您应该根据您的响应内容类型使用 result.responseText 或 result.responseJSON。因为“结果”只是成功事件的响应正文,而错误状态的响应正文 + 其他响应相关属性。

PS:$.ajax 的成功事件只满足 HTTP/200 结果,对于其他响应代码,它会导致错误事件触发。

【讨论】:

  • 很好解释,在进行以下更改后,它按预期工作:error: function (result) { self.result(JSON.stringify(result.responseJSON)); }。谢谢!
猜你喜欢
  • 1970-01-01
  • 2021-01-17
  • 2016-04-04
  • 2016-05-20
  • 2013-01-17
  • 2015-12-02
  • 2019-09-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多