Response JSON format changing depending on success/error: why?

Response JSON format changing depending on success/error: why?

我正在构建一个 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));
    }
});

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

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

其中 return 正是以下内容,因为它应该

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

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

您应该根据您的回复内容类型使用result.responseTextresult.responseJSON。因为 'result' 只是成功事件的 响应主体 响应主体 + 其他响应相关属性 错误状态。

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