Poul K. Sørensen Poul K. Sørensen - 1 month ago 7
C# Question

System.Net.WebException: The remote name could not be resolved:

I am testing an endpoint that I am experiencing some issues with.

I am simply using

in a loop that performs a request each hour.

var httpClient = new HttpClient();
var message = httpClient.GetAsync(url).Result;

Once in a while I am getting this exception:

System.Net.Http.HttpRequestException: An error occurred while sending
the request. ---> System.Net.WebException: The remote name could not
be resolved: 'xxx'

The experience is that right after the exception, the URL can be accessed. In a browser you simply refresh the page and all is good.

I still haven't got any reports from users experiencing it so I am wondering if it's just a local issue here but could use a little information to help diagnose.

Is there a way to check if The remote name could not be resolved is caused by an DNS issue or by a web server issue from the exceptions? Can I get more information out of
or do I need more advanced diagnostic tools?


It's probably caused by a local network connectivity issue (but also a DNS error is possible).

It may happen, there isn't much you can do.

What I'd suggest to always wrap that (network related) code in a loop with a try/catch block (as also suggested here for other fallible operations). Handle known exceptions, wait a little (say 1000 msec) and try again (for say 3 times). Only if failed all times then you can quit/report an error to your users. Very raw example like this:

private const int NumberOfRetries = 3;
private const int DelayOnRetry = 1000;

public static HttpResponseMessage GetFromUrl(string url) {
    for (int i=1; i <= NumberOfRetries; ++i) {
        try {
            // Also consider to make this method async and await this
            return new HttpClient().GetAsync(url).Result;
        catch (Exception e) {
            // DO BETTER THAN THIS! Catch what you want to handle,
            // not all exceptions worth a retry. Documentation and many
            // tests will help you to narrow a limited subset of
            // exceptions and error codes.

            // Last one, (re)throw exception and exit
            if (i == NumberOfRetries)

            // Many network related errors will recover "automatically"
            // after some time, exact delay is pretty arbitrary and
            // should be determined with some tests. 1 second is pretty
            // "good" for local I/O operations but network issues may
            // need longer delays.