gpt4 book ai didi

c# - 具有 HttpClientFactory 实现的动态代理

转载 作者:太空狗 更新时间:2023-10-30 00:59:36 30 4
gpt4 key购买 nike

我有 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 个应用程序,其中一个对我来说似乎不错:

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.处理每个请求的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 的情况下动态更改代理?

最佳答案

之后无法更改 HttpClientHandler 的任何属性或将新版本的 HttpClientHandler 分配给现有的 HttpClient它被实例化。因此,不可能为特定的 HttpClient 提供动态代理:您只能指定一个代理。

实现此目的的正确方法是使用命名客户端,并为每个代理端点定义一个客户端。然后,您需要注入(inject) IHttpClientFactory 并选择要使用的代理之一,请求实现该代理的指定客户端。

services.AddHttpClient("MyServiceProxy1").ConfigurePrimaryHttpMessageHandler(() =>
{
return new HttpClientHandler
{
Proxy = new WebProxy("http://127.0.0.1:8888"),
UseProxy = true
};
});

services.AddHttpClient("MyServiceProxy2").ConfigurePrimaryHttpMessageHandler(() =>
{
return new HttpClientHandler
{
Proxy = new WebProxy("http://127.0.0.1:8889"),
UseProxy = true
};
});

...

然后:

public class MyService : IMyInterface
{
private readonly HttpClient _client;

public MyService(IHttpClientFactory httpClientFactory)
{
_client = httpClientFactory.CreateClient("MyServiceProxy1");
}

public async Task CallHttpEndpoint()
{
var request = new HttpRequestMessage(HttpMethod.Get, "www.customUrl.com");
var response = await _client.SendAsync(request);
...
}
}

关于c# - 具有 HttpClientFactory 实现的动态代理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55574091/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com