Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read the error message from Request.CreateErrorResponse?

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?

like image 578
Prabhu Avatar asked Jan 05 '23 21:01

Prabhu


1 Answers

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"
}
like image 146
peco Avatar answered Jan 22 '23 20:01

peco