第一种是直接给service添加服务
var serviceCollection = new ServiceCollection();
serviceCollection
.AddHttpClient(NamedHttpClients.ProxiedClient)
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler() {
Proxy = httpProxy
});
var services = serviceCollection.BuildServiceProvider();
var httpClientFactory = services.GetService<IHttpClientFactory>();
var client = httpClientFactory.CreateClient(NamedHttpClients.ProxiedClient);
第二种是不通过IHttpfactory 创建客户端
var handler = new HttpClientHandler
{
Proxy = ...
};
var client = new HttpClient(handler)
{
Timeout = TimeSpan.FromSeconds(60),
};
//或者
private HttpClient ClientFactory()
{
var proxiedHttpClientHandler = new HttpClientHandler(){ UseProxy = true};
proxiedHttpClientHandler.Proxy = new WebProxy("proxy address");
var httpClient = new HttpClient(proxiedHttpClientHandler)
{
BaseAddress = new Uri("uri");
Timeout = 2000; //if you need timeout;
}
}
_createHttpClient = () => ClientFactory();
这种方法弊端在于未只用IHttpClientFactory创建,会频繁进行创建和销毁