C# 使HttpClient使用app.config defaultProxy

C# 使HttpClient使用app.config defaultProxy,c#,.net,model-view-controller,proxy,dotnet-httpclient,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,

我正在尝试使用
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中使用它


谢谢你的建议。

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

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

我仍然重视原始海报关于web.config defaultProxy的问题的答案。HttpClient可以使用此设置吗?
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);

}