简体   繁体   English

在Ajax onSuccess中阅读HttpResponseMessage

[英]Read HttpResponseMessage in Ajax onSuccess

This is my APIController method - 这是我的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;
}

This is my ajax call to above method - 这是我对上述方法的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);
    }
});

I am not able to read the HttpResponseMessage returned by the API Method. 我无法读取API方法返回的HttpResponseMessage。 For both the conditions of OK and Bad Request, status code returned in 'xhr' of ajax method is '204' & 'No Content'. 对于OK和Bad Request的条件,ajax方法的'xhr'中返回的状态码为'204'和'No Content'。 I need to validate based on response code. 我需要根据响应代码进行验证。 Any help pls! 任何帮助请!

I tried success: function(response) too, response was undefined. 我尝试成功:功能(响应)也是如此,响应未定义。

The response is 204 No content because you literally don't add any content. 响应为204 No content因为您实际上不添加任何内容。 All you're doing is setting the response code. 您要做的就是设置响应代码。 You can add content to the response like this: 您可以像这样向响应添加内容:

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

Alternatively use the Request.CreateResponse() / CreateErrorResponse() to create the HttpResponseMessage for you: 或者,使用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");
}

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

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