在Ajax onSuccess中读取HttpResponseMessage

时间:2016-09-29 10:14:37

标签: javascript c# jquery ajax asp.net-web-api

这是我的APIController方法 -

[HttpPost]
public HttpResponseMessage Get(string url) {
    string responseString = GetWebApiData(url);

    HttpResponseMessage response = new HttpResponseMessage();

    if (!string.IsNullOrEmpty(responseString) && responseString.ToString().IsValid()) {
        response.ReasonPhrase = "Valid";
        response.StatusCode = HttpStatusCode.OK;
    } else {
        response.ReasonPhrase = "Invalid";
        response.StatusCode = HttpStatusCode.BadRequest;
    }

    return response;
}

这是我对上述方法的ajax调用 -

$.ajax({
    type: "POST",
    url: "http://localhost:50/api/DC/" + formData,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(data, textStatus, xhr) {


    },
    failure: function(response) {
        alert(response.responseText);
    },
    error: function(response) {
        alert(response.responseText);
    }
});

我无法读取API方法返回的HttpResponseMessage。对于OK和Bad Request的条件,在ajax方法的'xhr'中返回的状态代码是'204'& '无内容'。我需要根据响应代码进行验证。任何帮助!

我也尝试了成功:功能(响应),响应未定义。

1 个答案:

答案 0 :(得分:0)

响应为204 No content,因为您确实不添加任何内容。您所做的只是设置响应代码。您可以像这样在响应中添加内容:

response.Content = new StringContent("Return data goes here");

或者使用Request.CreateResponse() / CreateErrorResponse()为您创建HttpResponseMessage

[HttpPost]
public HttpResponseMessage Get(string url)
{
    string responseString = GetWebApiData(url);
    if (!string.IsNullOrEmpty(responseString) && responseString.ToString().IsValid())
    {
        return Request.CreateResponse("Valid"); // I'd suggest returning an object here to be serialised to JSON or XML
    }

    return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Invalid");
}