【发布时间】: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