简体   繁体   English

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

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

I'm building a Web Api, using an Ajax call to test an action for uploading files. 我正在构建一个Web Api,使用Ajax调用来测试上传文件的操作。

The Ajax looks just like this: 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));
    }
});

In my action, I want to return a JSON custom object if there's an error, such as: 在我的操作中,如果发生错误,我想返回一个JSON自定义对象,例如:

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

which returns exactly the following, as it should 它应返回正确的以下内容

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

But if instead of using HttpStatusCode.OK I use any other, such as HttpStatusCode.NotFound in exactly the same call that I have above: 但是,如果不是使用HttpStatusCode.OK我使用任何其他诸如HttpStatusCode.NotFound恰好我有上述相同的呼叫:

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

I get this result instead: 我得到了这个结果:

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

Why? 为什么? And how do I get rid of it? 我该如何摆脱呢?

You should use result.responseText or result.responseJSON according to your response content type. 您应该根据您的响应内容类型使用result.responseTextresult.responseJSON Because the 'result' is just response body for success event but response body + other response related properties for the error state. 因为“结果”只是成功事件的响应主体 ,而是错误状态的响应主体其他与响应相关的属性

PS: $.ajax's success event only satisfies with HTTP/200 results and for the other reponse codes, it causes the error event fire. PS:$ .ajax的成功事件仅满足HTTP / 200结果,对于其他响应代码,它将导致错误事件触发。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM