响应JSON格式根据成功/错误而变化:为什么?

时间:2016-01-20 11:25:12

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

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

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

1 个答案:

答案 0 :(得分:2)

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

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

相关问题