简体   繁体   English

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

[英]Status Code is 200 but still error event fires in ajax call to MVC web API

I am posting some strings on a MVC based web api using [FromBody] which is working fine. 我正在使用[FromBody]正常工作在基于MVC的Web api上发布一些字符串。 Data is adding in database. 数据正在添加到数据库中。 My Controller's Action method type is HttpResponseMessage and i am returning this response 我的控制器的Action方法类型为HttpResponseMessage,我正在返回此响应

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

but error event is firing instead of success. 但是错误事件正在触发而不是成功。

Here is the ajax call. 这是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);
    }
});

Suggest me something to solve this issue. 建议我一些解决此问题的方法。

I found out the solution for this question. 我找到了这个问题的解决方案。 Need to set two things. 需要设置两件事。 First is to set the value of custom header in web.config of MVC Web Api ie Access-Control-Allow-Origin (the value should be the origin URL from where API is to be called). 首先是在MVC Web Api的web.config中设置自定义标头的值,即Access-Control-Allow-Origin(该值应该是调用API的原始URL)。 And second one is more important. 第二个更重要。 "datatype" in ajax call is "json" so it was expecting a valid JSON result from API, Whereas the result returning from API is just a HTTPResponseMessage having code 200 and a string "value". Ajax调用中的“数据类型”为“ json”,因此它期望从API获得有效的JSON结果,而从API返回的结果只是具有代码200和字符串“值”的HTTPResponseMessage。 I figured out that the error is parsingerror. 我发现错误是parsingerror。 So here i returned a valid json object instead of string "value". 所以在这里我返回了一个有效的json对象,而不是字符串“ value”。

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

it worked for me and success event of ajax call fired. 它为我工作,并且成功触发了ajax调用事件。 Bingo :) 答对了 :)

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

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