How to read the error message from Request.CreateErrorResponse?

My WebAPI method returns an error response:

return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Something bad happened");

At my client end (MVC project) I want to display an error message, but could not get the message “Something bad happened” to display:

var response = await client.SendAsync(request);
if (!response.IsSuccessStatusCode)
{
    ViewBag.Error= response.ReasonPhrase; 
}

Besides ReasonPhrase, I have tried response.ToString(), response.Content.ToString()and response.Content.ReadAsStringAsync(). None of them received me a message. Why can Postman display a message?

Any ideas on how I can access the message line?

+4
source share
3 answers

application/json, Json.Net :

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"
}
+4

, response.Content.ReadAsStringAsync() a Task<string>, a string.

response.Content.ReadAsStringAsync().Result 

async, .

string message = await response.Content.ReadAsStringAsync();
+3

What am I doing to get an error message. when debugging is complete, you can change the return type

       public string someRequest()
    {
        try
        {
            var response = await client.SendAsync(request);
            return "Ok";
        }
        catch (Exception e)
        {
         return e.Message;
        }
    }
0
source

All Articles