It has a method CreateClient which returns the HttpClient Object. But in reality, HttpClient is just a wrapper, for HttpMessageHandler. HttpClientFactory manages the lifetime of HttpMessageHandelr, which is actually a HttpClientHandler who does the real work under the hood.
Not only that HttpClientFactory can create and manage new HttpClient instances but also, it works with underlying handlers. Basically, when creating new HttpClient instances, it doesn't recreate a new message handler but it takes one from a pool. Then, it uses that message handler to send the requests to the API.
In general, HttpClientHandler can be used to configure a specific configuration like custom policy, headers, or security mechanism, compression, certificates, etc. We shall cover the below aspects in this article, Configure HttpClientHandler for Authentication Example: Bearer or Basic.
With the new HttpClientFactory in ASP.NET Core 2.1, it's quite easy to configure custom HTTP clients with things like base urls, default headers etc.
However, I haven't found a way to centralize configuration that lets me inject headers from the current request context. For example, consider a service called with an Authorization
header, which I wish to pass on to all the underlying services as well. It would be awesome to be able to configure this in the .AddHttpClient()
call on services
in the Startup
class, but I can't figure out how to get at the request context from there.
Any ideas?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With