简体   繁体   中英

Read HttpResponseMessage in Ajax onSuccess

This is my APIController method -

[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({
    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. For both the conditions of OK and Bad Request, status code returned in 'xhr' of ajax method is '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. 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:

[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");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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