How to retrieve message from WEB API?

Vadim picture Vadim · Jan 28, 2013 · Viewed 21k times · Source

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.

Answer

Jeff picture Jeff · Jan 31, 2013

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