c# - 让 HttpClient 使用 app.config defaultProxy

标签 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 中使用它?

感谢您的任何想法。

最佳答案

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

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

并在您的应用程序中读取该 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);

}

关于c# - 让 HttpClient 使用 app.config defaultProxy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45818300/

相关文章:

.net - Azure 移动服务与设备作为服务器的 Web 套接字

ruby-on-rails - 如何根据rails中的user_id过滤所有帖子?

c# - 如何检测用户控件是在 IDE 中、在 Debug模式中还是在发布的 EXE 中运行?

.net - 什么时候AppDomain.ProcessExit不会被调用?

.net - Windows 7 和 Windows 8 中的 ListBox 边距不一样

node.js - 在 Node/Express 服务器中使用 async/await 是个坏主意吗?

javascript - Sencha Architect 自动创建 ViewModel 和 View Controller

c# - 在 C# 中调用静态方法

c# - 基类扩展的 Visual Studio 2010 编译器错误

c# - 如何只读取添加到事件日志的新事件?