My WebAPI method returns an error response:
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Something bad happened");
On my client end (an MVC project), I want to display the error message, but unable to get the message "Something bad happened" to display:
var response = await client.SendAsync(request);
if (!response.IsSuccessStatusCode)
{
ViewBag.Error= response.ReasonPhrase;
}
Other than ReasonPhrase, I've tried response.ToString()
, response.Content.ToString()
, and response.Content.ReadAsStringAsync()
. None of them get me the message. How come Postman is able to display the message?
Any ideas how I can access the message string?
If your response content comes back as application/json
, you can deserialize it with Json.Net
like this:
if(!response.IsSuccessStatusCode)
{
var errors = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object>>(response.Content.ReadAsStringAsync().Result);
var message = errors[HttpErrorKeys.MessageKey];
// message is "Something bad happened"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With