Is the .NET Core HttpClient the concept of interceptors?

I would like to include some synchronization logic in all calls made through HttpClient from my ASP.NET Core application, including calls made from third-party libraries.

Does the .NET Core HttpClient have something that I can connect to run code on every request?

+5
source share
1 answer

Yes Yes. HttpClient issues an HTTP request through the DelegatingHandler chain. To intercept an HttpClient request, you can add a derived handler with an overridden SendAsync method to this chain.

Using:

 var handler = new ExampleHttpHandler(fooService); var client = new HttpClient(new ExampleHttpHandler(handler)); var response = await client.GetAsync("http://google.com"); 

Implementation:

 public class ExampleHttpHandler : DelegatingHandler { //register the handler itself in DI to inject dependencies public ExampleHttpHandler(FooService service) : this(service, null) { } public ExampleHttpHandler(FooService service, HttpMessageHandler innerHandler) { //default handler should be the last! InnerHandler = innerHandler ?? new HttpClientHandler(); } protected override async Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { //add any logic here return await base.SendAsync(request, cancellationToken); } } 
+4
source

Source: https://habr.com/ru/post/1264004/


All Articles