Search code examples
restsharp

How to use WebProxy with RestSharp?


I would like to know how to use WebProxy with RestSharp. I am using version 108.0.1 and the code given below returns 407 when running locally from my workstation, which should use my credentials.

   var client = new RestClient("https://www.google.com");
   var proxy = new System.Net.WebProxy("http://mycorpproxy.com");
   proxy.UseDefaultCredentials = true;
   client.Options.Proxy = proxy;
   var request = new RestRequest();
   request.Method = Method.Get;
   var response = client.Execute(request);

Solution

  • You need to specify the proxy in the options when you create the client, not after. In v107, the options object properties were init-only, but it fails on legacy SDKs, so we had to revert it to setters, but setting the options that are used to create an HttpClient instance after the client is created has no effect.

    var proxy = new WebProxy("http://mycorpproxy.com") {
        UseDefaultCredentials = true
    };
    var options = new RestClientOptions("https://www.google.com") {
        Proxy = proxy
    };
    var client = new RestClient(options);