问题
I have the following issue. I have a proxy set. If a request via proxy very slow or has crashed I would like to try again without proxy.
For setting proxy I have the following code in the Startup.cs
file:
services.AddHttpClient<ICheckPackagesService, CheckPackagesService>(x =>
{
x.Timeout = TimeSpan.FromSeconds(10);
}).ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler
{
Proxy = new WebProxy(IpService.GetIp())
});
But I can't imagine what I have to do for sending new one request without proxy (if the previous one has crashed of course!). A fast research in the official documentation gives me nothing.
Please, share your experience for this case. Thank you!
P.S. I use .NET Core 2.2.401
.
回答1:
You cannot change the any of the properties of HttpClientHandler or assign a new version of HttpClientHandler to an existing HttpClient after it is instantiated.
Therefore you cannot use a Polly retry policy configured via HttpClientFactory to call via a new proxy (Polly policies configured via HttpClientFactory are applied as a DelegatingHandler within HttpClient).
As stated in the first link, use named clients defined on IHttpClientFactory instead, and define a named client for each proxy endpoint.
来源:https://stackoverflow.com/questions/58708315/how-i-can-change-configuration-of-httpmessagehandler-from-polly-retry