Suganya M K
Suganya M K

Reputation: 33

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.

Upvotes: 0

Views: 6195

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

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

Upvotes: 1

Related Questions