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