Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve message from WEB API?

I created some web apis and when an error happens the api returns HttpResponseMessage that is created with CreateErrorResponse message. Something like this:

return Request.CreateErrorResponse(
              HttpStatusCode.NotFound, "Failed to find customer.");

My problem is that I cannot figure out how to retrieve the message (in this case "Failed to find customer.") in consumer application.

Here's a sample of the consumer:

private static void GetCustomer()
{
    var client = new HttpClient();
    client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));
    string data =
        "{\"LastName\": \"Test\", \"FirstName\": \"Test\"";

    var content = new StringContent(data, Encoding.UTF8, "application/json");

    var httpResponseMessage = 
                 client.PostAsync(
                    new Uri("http://localhost:55202/api/Customer/Find"),
                    content).Result;
    if (httpResponseMessage.IsSuccessStatusCode)
    {
        var cust = httpResponseMessage.Content.
                  ReadAsAsync<IEnumerable<CustomerMobil>>().Result;
    }
}

Any help is greatly appreciated.

like image 633
Vadim Avatar asked Jan 28 '13 14:01

Vadim


People also ask

Can we return File result from API?

Return a File in Web API As a Stream Finally, we return a call to the File method. Note that this time we are passing a Stream object instead of a byte[] as the first parameter. This is possible because the File method has many overloads.

Can WebAPI return view?

You can return one or the other, not both. Frankly, a WebAPI controller returns nothing but data, never a view page. A MVC controller returns view pages. Yes, your MVC code can be a consumer of a WebAPI, but not the other way around.

How do I display a success message in Web API?

In the GET method, get the message from ResponseMessage instance by passing the enum value as parameter. Run the application and you can see a response message as 'Successful! '


1 Answers

Make sure you set the accept and or content type appropriately (possible source of 500 errors on parsing the request content):

client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

content.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/json");

Then you could just do:

var errorMessage = response.Content.ReadAsStringAsync().Result;

That's all on the client of course. WebApi should handle the formatting of the content appropriately based on the accept and/or content type. Curious, you might also be able to throw new HttpResponseException("Failed to find customer.", HttpStatusCode.NotFound);

like image 90
Jeff Avatar answered Sep 22 '22 04:09

Jeff