使HttpClient使用app.config defaultProxy

时间:2017-08-22 12:56:07

标签: c# .net model-view-controller proxy dotnet-httpclient

我正在尝试使用HttpClient与代理后面的api交谈。但由于代理仅对当前环境有效,我不希望它被硬编码。

这就是我目前正在做的事情:

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

这就是我想要使用的内容:

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

是否有可能在app / web.config中定义代理并在每个默认值的HttpClient中使用它?

感谢您的任何想法。

1 个答案:

答案 0 :(得分:1)

永远不要在你的应用程序中使用硬编码设置,你有app.config,只需在appSettings标签下添加你的设置:

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

并在您的应用程序中读取该密钥

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

}

相关问题