PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, September 20, 2022

[FIXED] How to retrieve message from WEB API?

 September 20, 2022     asp.net-web-api, consumer     No comments   

Issue

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.


Solution

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



Answered By - Jeff
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing