From .net Core 2+ MS gave us a way to add policies to the HttpClient that will work as long as the client is injected through the IOC container. But this led me to a doubt I can't seem to figure out while endlessly googling. What if we want to override the HttpClient policies while still using the HttpClientFactory and DI to inject the client into a provider? Can we "turn off" the policies for a specific request or can we add extra Policies while overriding the global ones defined on the Startup ?
Asked
Active
Viewed 1,856 times
1
-
Edited my original answer to highlight a way that this is possible – mountain traveller Jan 25 '20 at 00:32
1 Answers
4
Use different named clients or typed clients to define separate logical HttpClient
configurations.
OR
When configuring policies using IHttpClientFactory
, you can use .AddPolicyHandler(...)
overloads or .AddPolicyHandlerFromRegistry(...)
overloads which allow you to select the policy based on information in the HttpRequestMessage
. This can permit varying the policies applied for different requests.
To take an example from the Polly and HttpClientFactory documentation, one use case might be to apply a Retry policy only to GET requests but not other http verbs:
var retryPolicy = HttpPolicyExtensions
.HandleTransientHttpError()
.WaitAndRetryAsync(new[]
{
TimeSpan.FromSeconds(1),
TimeSpan.FromSeconds(5),
TimeSpan.FromSeconds(10)
});
var noOpPolicy = Policy.NoOpAsync().AsAsyncPolicy<HttpResponseMessage>();
services.AddHttpClient(/* etc */)
// Select a policy based on the request: retry for Get requests, noOp for other http verbs.
.AddPolicyHandler(request => request.Method == HttpMethod.Get ? retryPolicy : noOpPolicy);

mountain traveller
- 7,591
- 33
- 38
-
2Thats not quite what I was looking for but its probably what I will have to use. I wanted to , while injecting a TypedClient override the policies that are alredy on this typed client and then use whatever I want for a given scope. – Gonçalo Castilho Jan 27 '20 at 08:34