Sunday, January 14, 2024

HttpClient: Dynamically Add HttpMessageHandlers

In this post, let's have a look at how we can create a HttpClient with HttpMessageHandlers that gets created at run time.

I was hoping IHttpClientFactory would support that, but at least I couldn't find a way to get IHttpClientFactory to work with dynamic HttpMessageHandlers.

But luckily we have HttpClientFactory static class and there we have HttpClientFactory.Create(HttpMessageHandler, DelegatingHandler[])

The basic logic is we are supplying the innermost handler and other handlers, and internally it would get wired as a pipeline, something like below.

public static HttpMessageHandler CreatePipeline(HttpMessageHandler innerHandler, IEnumerable<DelegatingHandler> handlers)
HttpMessageHandler httpMessageHandler = innerHandler;
    foreach (DelegatingHandler item in handlers.Reverse())
        item.InnerHandler = httpMessageHandler;
        httpMessageHandler = item;

return httpMessageHandler;

And then it would create a HttpClient with the chained HttpMessageHandler as follows.

new HttpClient(CreatePipeline(innerHandler, handlers));

Hope this helps.

Happy Coding.


No comments:

Post a Comment