Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Azaferany/3611e2e816287e1fe5d63b629cbbb4cb to your computer and use it in GitHub Desktop.
Save Azaferany/3611e2e816287e1fe5d63b629cbbb4cb to your computer and use it in GitHub Desktop.
add handler to all http client (Configuring ALL HttpClients named or unnamed)
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Http;
using Microsoft.Extensions.Options;
using Polly;
using Prometheus;
var services = new ServiceCollection();
services.AddSingleton<IHttpMessageHandlerBuilderFilter, DefaultHttpMessageHandlerBuilderFilter>();
// added handlers to this client will apply to all http clients
services.AddHttpClient(DefaultHttpMessageHandlerBuilderFilter.GlobalMessageHandlerConfigure)
.AddTransientHttpErrorPolicy(p => p.WaitAndRetryAsync(3, _ => TimeSpan.FromMilliseconds(60)))
.AddPolicyHandler(Policy.TimeoutAsync<HttpResponseMessage>(10));
services.AddHttpClient("example", client => client.BaseAddress = new Uri("http://example.com"))
.UseHttpClientMetrics();
var provider = services.BuildServiceProvider();
var httpClientFactory = provider.GetRequiredService<IHttpClientFactory>();
//http client with Polly Retry + Polly Timeout + Prometheus-net Metrics
var httpClient = httpClientFactory.CreateClient("example");
httpClient.GetAsync("/");
/// <summary>
/// add all handlers of GlobalMessageHandlerConfigure client to all clients
/// https://github.com/dotnet/AspNetCore.Docs/issues/18162
/// </summary>
public class GlobalHttpMessageHandlerBuilderFilter : IHttpMessageHandlerBuilderFilter
{
public const string GlobalMessageHandlerConfigure = nameof(GlobalMessageHandlerConfigure);
public Action<HttpMessageHandlerBuilder> Configure(Action<HttpMessageHandlerBuilder> next) =>
handlerBuilder =>
{
next(handlerBuilder);
if (handlerBuilder.Name != GlobalMessageHandlerConfigure)
{
var clientFactoryOptions = handlerBuilder.Services
.GetRequiredService<IOptionsMonitor<HttpClientFactoryOptions>>().Get(GlobalMessageHandlerConfigure);
if (clientFactoryOptions is not null)
foreach (var builderAction in clientFactoryOptions.HttpMessageHandlerBuilderActions)
builderAction(handlerBuilder);
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment