WebApi: Reading errors

81 views Asked by At

I've got a simple web api which is consumed from a mvc project, I keep on getting the 'Response status code does not indicate success' and was wondering how would I get the response body from the error, I can see the error within a rest viewer but can't navigate through to the error. This is the following code within the MVC app

public ActionResult Index()
    {

        try
        {
            var uri = "http://localhost:57089/api/values";

            using (var client = new HttpClient())
            {
                Task<string> response =  client.GetStringAsync(uri);

                object result = JsonConvert.DeserializeObject(response.Result);

                return (ActionResult) result;

            }


        }
        catch (Exception ex)
        {
            return Content(ex.ToString());
        }

        return View();
    }

Within the API controller I'm sending a bad request, here's the code

        public IHttpActionResult Get()
        {

        return BadRequest("this is a very bad request " + System.DateTime.Now.ToUniversalTime());

        }

I've tried to use WebException, HttpRequestException as exceptions to catch the error with no luck.

I can see the response body within the rest viewer

WebApi Viewier

I want to be able to navigate to the Error Message so I can pass that to the client (which later will be changed to a guid).

[EDITED]

I've got a solution without using GetStringAsync, but wanted to use that if possible.

Here's the solution

 var httpClient = new HttpClient();
            httpClient.BaseAddress = new Uri(url);
            HttpResponseMessage responseMessage = httpClient.GetAsync("").Result;

            if (responseMessage.IsSuccessStatusCode) return Content(responseMessage.ToString());
            var a = responseMessage.Content.ReadAsStringAsync().Result;

            var result = JsonConvert.DeserializeObject<HttpError>(a);

            object value = "";

            return Content(result.TryGetValue("ErrorMessage", out value) ? value.ToString() : responseMessage.ToString());

Is there a better way?

1

There are 1 answers

4
David Tansey On

Using WebException you should be able to get to the ResponseStream and the custom error message like this:

catch (WebException e)
{
    var message = e.Message;
    using (var reader = new StreamReader(e.Response.GetResponseStream()))
    {
        var content = reader.ReadToEnd();
    }
}

Hope that helps.