将客户端添加到服务集合时,您应该能够在那里配置处理程序
使用命名客户端方法,我将使用一个常量来保存客户端名称。
public static class NamedHttpClients {
public const string ProxiedClient = "ProxiedClient";
}
从那里只需要配置客户端
//...
var serviceCollection = new ServiceCollection();
serviceCollection
.AddHttpClient(NamedHttpClients.ProxiedClient)
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler() {
Proxy = httpProxy
});
var services = serviceCollection.BuildServiceProvider();
这样当通过已解析调用客户端时IHttpClientFactory
var httpClientFactory = services.GetService<IHttpClientFactory>();
var client = httpClientFactory.CreateClient(NamedHttpClients.ProxiedClient);
返回的客户端将使用带有代理的处理程序。