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.
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);
}