状态代码为 200,但在对 MVC Web API 的 ajax 调用中仍会触发错误事件

本文关键字:调用 ajax 事件 错误 API 代码 Web MVC 状态 | 更新日期: 2023-09-27 18:30:30

我正在使用[FromBody]在基于MVC的Web api上发布一些字符串,它工作正常。数据正在添加到数据库中。我的控制器的操作方法类型是 HttpResponseMessage,我返回此响应

HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, "value"); 
return response;

但是错误事件正在触发而不是成功。

这是 ajax 调用。

$.ajax({
    type: 'POST',
    url: 'http://businessworxapi.azurewebsites.net/api/SaveTemplate',
    contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
    dataType: "text json",
    data: "RetailerID=" + encodeURIComponent(retailerid) + "&SvgContent=" +
            encodeURIComponent(stringsvg) + "&Description=" +
            encodeURIComponent(Description) + "&TemplateName=" +
            encodeURIComponent(Name),
    beforeSend: function () {
    },
    success: function (response) {
        alert("Added");
    },
    error: function (xhr, ajaxOptions, thrownError) {
        alert(xhr.responseText);
    }
});

建议我解决这个问题。

状态代码为 200,但在对 MVC Web API 的 ajax 调用中仍会触发错误事件

我找到了这个问题的解决方案。需要设置两件事。首先是在 MVC Web API 的 web.config 中设置自定义标头的值,即 Access-Control-Allow-Origin(该值应该是要调用 API 的源 URL)。第二个更重要。ajax 调用中的"datatype"是"json",因此它期望来自 API 的有效 JSON 结果,而从 API 返回的结果只是一个具有代码 200 和字符串"值"的 HTTPResponseMessage。我发现错误是解析错误。所以这里我返回了一个有效的 json 对象而不是字符串"value"。

HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK , new { responseValue = "Value" });
return response;

它对我有用,Ajax Call的成功事件被解雇了。宾果:)