DNS resolution failure in HttpClient throws Unhandled AggregateException

浪子不回头ぞ 提交于 2019-12-11 12:41:02

问题


I have a .NET 4 client app using HttpClient. When the _tokenServiceUrl does not correctly resolve via DNS (for example: a network change change occurs when a VPN goes up or down or when mobile devices lose connectivity in a dead spot) then an AggregateException gets thrown. I'm trying to catch that exception, but can't.

    try
    {
        var response = _client.GetAsync(_tokenServiceUrl).Result;

        response.EnsureSuccessStatusCode();
        var token = response.Content.ReadAsAsync<string>().Result;
        return token;

    }
    catch (AggregateException exception)
    {
        Disconnected(exception);
        return string.Empty;
    }

I've mucked around with adding a ContinueWith in order to trap the exception and handle it, but I never return. What can I do to kill the task, given such an exception?


回答1:


You should be able to capture that Aggregate exception.

Make sure you are not running Fiddler, or some other proxy, when testing. If you do, then an exception won't occur during the GetAsync. You will just get at 502 response and then EnsureSuccessStatusCode will throw a HttpRequestException.



来源:https://stackoverflow.com/questions/22024856/dns-resolution-failure-in-httpclient-throws-unhandled-aggregateexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!