0

I am using GetAsync method to read a web api get method through the following code

        HttpClient client = new HttpClient();
        client.BaseAddress = new Uri("http://localhost:10000/");

        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        HttpResponseMessage response = client.GetAsync("api/account/balance/" + accountNumber.ToString()).Result;
        if (response.IsSuccessStatusCode)
        {
            string responseJson = response.Content.ReadAsStringAsync().Result;

            JavaScriptSerializer jss = new JavaScriptSerializer();
            var result = jss.Deserialize<AccountResponse>(responseJson);
        }
        else
        {
            Console.WriteLine("Error! Http error " + response.StatusCode.ToString());
            Console.ReadLine();
        }

I am expecting when there is a problem with the service like authentication, page not found, or else, the relevant HTTP code should be returned and found in the HttpResponseMessage instance, but what happens is that when one of these HTTP error exist, the HttpResponseMessage throws an AggregateException when trying to GetAsync

1
  • Are you sure that you're actually getting one of those errors and there's not a bigger issue that would result in an exception? Try pointing your client at httpbin.org/status/404 , this should get you a response message with a 404 code and no exception. Commented Jan 23, 2018 at 19:00

1 Answer 1

1

Most likely, the aggregate exception is showing because your Task operation is throwing one or more exceptions. Per design Task methods always throws all its exceptions in an aggregated exception and to get the real exceptions await your tasks by using the async - await pattern

using(var client = new HttpClient())
{
    client.BaseAddress = new Uri("http://localhost:10000/");
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    HttpResponseMessage response = await client.GetAsync("api/account/balance/" + accountNumber.ToString());
    if (response.IsSuccessStatusCode)
    {
        string responseJson = await response.Content.ReadAsStringAsync();

        JavaScriptSerializer jss = new JavaScriptSerializer();
        var result = jss.Deserialize<AccountResponse>(responseJson);
    }
    else
    {
        Console.WriteLine("Error! Http error " + response.StatusCode.ToString());
        Console.ReadLine();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.