.nethttpproxypollyresiliency

Retry HTTP request from .NET with different proxy server


I can issue HTTP requests through a proxy in a .NET app. There are a number of proxy servers I can use and sometimes one or more will go down. How can I have my app retry the HTTP request using a different proxy? I am open to any suggestion and have heard good things about Polly for adding resiliency.


Solution

  • For my use case, it turns out that I was better off without Polly.

    public static string RequestWithProxies(string url, string[] proxies)
    {
        var client = new WebClient
        {
            Credentials = new NetworkCredential(username, password)
        };
        var result = String.Empty;
    
        foreach (var proxy in proxies)
        {
            client.Proxy = new WebProxy(proxy);
            try
            {
                result = client.DownloadString(new Uri(url));
            }
            catch (Exception) { if (!String.IsNullOrEmpty(result)) break; }
        }
    
        if (String.IsNullOrEmpty(result)) throw new Exception($"Exhausted proxies: {String.Join(", ", proxies)}");
        return result;
    }