【发布时间】:2019-04-08 12:59:46
【问题描述】:
我有Asp.Net Core WebApi。我正在根据HttpClientFactory pattern 发出 Http 请求。这是我的示例代码:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddHttpClient<IMyInterface, MyService>();
...
}
public class MyService: IMyInterface
{
private readonly HttpClient _client;
public MyService(HttpClient client)
{
_client = client;
}
public async Task CallHttpEndpoint()
{
var request = new HttpRequestMessage(HttpMethod.Get, "www.customUrl.com");
var response = await _client.SendAsync(request);
...
}
}
我想通过动态代理实现发送请求。这基本上意味着我可能需要为每个请求更改代理。至于现在,我发现了 2 个 approuces,其中没有一个对我来说似乎不错:
1.有一个像这样的静态代理:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddHttpClient<IMyInterface, MyService>().ConfigurePrimaryHttpMessageHandler(() =>
{
return new HttpClientHandler
{
Proxy = new WebProxy("http://127.0.0.1:8888"),
UseProxy = true
};
});
...
}
但在这种方法中,我只能为每个服务设置一个代理。
2.Dispose HttpClient 处理每个请求:
HttpClientHandler handler = new HttpClientHandler()
{
Proxy = new WebProxy("http://127.0.0.1:8888"),
UseProxy = true,
};
using(var client = new HttpClient(handler))
{
var request = new HttpRequestMessage(HttpMethod.Get, "www.customUrl.com");
var response = await client.SendAsync(request);
...
}
但是这样我就违反了 HttpClientFactory 模式,它可能会导致应用程序性能出现问题,如下面的article 所述
是否有第三种方法可以在不重新创建 HttpClient 的情况下动态更改代理?
【问题讨论】:
-
据此贴:docs.microsoft.com/en-us/dotnet/standard/… 每次从 IHttpClientFactory 获取 HttpClient 对象时,都会返回一个新实例。但是每个 HttpClient 使用一个由 IHttpClientFactory 汇集和重用的 HttpMessageHandler 来减少资源消耗,只要 HttpMessageHandler 的生命周期没有过期。所以它是有范围的,但有额外的好处。
标签: c# asp.net-core dotnet-httpclient