HttpClient通过AggregateException而不是返回HTTP代码

时间:2018-01-23 18:52:51

标签: c# asp.net-web-api httpclient

我正在使用GetAsync方法通过以下代码读取web api get方法

        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();
        }

我希望当验证服务出现问题,找不到页面时,否则,应该在HttpResponseMessage实例中返回并找到相关的HTTP代码,但是当出现其中一个HTTP错误时会发生什么,HttpResponseMessage在尝试GetAsync时抛出AggregateException

1 个答案:

答案 0 :(得分:0)

最有可能的是,聚合异常正在显示,因为您的Task操作会抛出一个或多个异常。 每个设计任务方法总是在聚合异常中抛出所有异常并获得真正的异常 等待您的任务使用async - await模式

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();
    }
}