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

前端 未结 3 964
栀梦
栀梦 2020-11-30 05:24

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

I am simply using HttpClient in a loop that performs a request each hour.



        
相关标签:
3条回答
  • 2020-11-30 06:08

    I had a similar issue when trying to access a service (old ASMX service). The call would work when accessing via an IP however when calling with an alias I would get the remote name could not be resolved.

    Added the following to the config and it resolved the issue:

    <system.net>
        <defaultProxy enabled="true">
        </defaultProxy>
    </system.net>
    
    0 讨论(0)
  • 2020-11-30 06:10

    Open the hosts file located at : **C:\windows\system32\drivers\etc**.

    Hosts file is for what?

    Add the following at end of this file :

    YourServerIP YourDNS

    Example:

    198.168.1.1 maps.google.com

    0 讨论(0)
  • 2020-11-30 06:23

    It's probably caused by a local network connectivity issue (but also a DNS error is possible). Unfortunately HResult is generic, however you can determine the exact issue catching HttpRequestException and then inspecting InnerException: if it's a WebException then you can check the WebException.Status property, for example WebExceptionStatus.NameResolutionFailure should indicate a DNS resolution problem.


    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 async Task<HttpResponseMessage> GetFromUrlAsync(string url) {
        using (var client = new HttpClient()) {
            for (int i=1; i <= NumberOfRetries; ++i) {
                try {
                    return await client.GetAsync(url); 
                }
                catch (Exception e) when (i < NumberOfRetries) {
                    await Task.Delay(DelayOnRetry);
                }
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题