Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make HttpClient use app.config defaultProxy

I'm trying to use an HttpClient to talk to an api behind a proxy. But because the proxy is valid only for the current environment, I don't want it to be hardcoded.

This is what I'm doing currently:

public static HttpClient CreateClient()
{
  var cookies = new CookieContainer();
  var handler = new HttpClientHandler
  {
    CookieContainer = cookies,
    UseCookies = true,
    UseDefaultCredentials = false,
    UseProxy = true,
    Proxy = new WebProxy("proxy.dev",1234),
  };
  return new HttpClient(handler);
}

This is what I would like to use:

<system.net> 
  <defaultProxy> 
    <proxy bypassonlocal="true" 
           usesystemdefault="false" 
           proxyaddress="http://proxy.dev:1234" /> 
  </defaultProxy>
</system.net>

Is there any possibility to define the proxy inside the app/web.config and use it in my HttpClient per Default?

Thanks for any idea you have.

like image 565
chrosey Avatar asked Feb 11 '26 16:02

chrosey


1 Answers

never use hardcoded settings in your application, you have app.config for that, just add your settings under appSettings tag:

  <appSettings>
    <add key="proxyaddress" value="proxy.dev:1234" /> 
  </appSettings>

and in your application read that key

public static HttpClient CreateClient()
{
  readonly static string[] proxyAddress = ConfigurationManager.AppSettings["proxyaddress"].Split(':');
  var cookies = new CookieContainer();
  var handler = new HttpClientHandler
  {
    CookieContainer = cookies,
    UseCookies = true,
    UseDefaultCredentials = false,
    UseProxy = true,
    Proxy = new WebProxy(proxyAddress[0],proxyAddress[1]),
  };
  return new HttpClient(handler);

}
like image 89
Leon Barkan Avatar answered Feb 14 '26 06:02

Leon Barkan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!