In last article, we have seen a basic example showing how http client middleware can be used to create an HttpClient instance using IHttpClientFactory. In this article, we will see an example of what named http clients are and how they can be used.
IHttpClientFactory provides a single place for providing and configuring a logical HttpClient instance. Each HttpClient instance encapsulates the configurations required for HTTP communication (e.g. headers, stream vs buffer mode, etc.).
For calling any APIs, generally there are few settings which are required. For example, if the API is subscription based, then it might be a requirement to send the API key in request headers.
So, every time an HttpClient instance is created, as a developer, we need to set few properties before making the request. If this code is going to be scattered at multiple places, then you might want to have a single place where all these settings can be set. This can be achieved by using the Http Client middleware.
AddHttpClient provides a way to centralize all the HTTP client configurations at one place. Named clients are a good choice when:
- The app requires many distinct uses of
HttpClients have different configuration.
Using the middleware, we can name an HTTP instance, and for every named instance, additional configurations can be specified.
Below code example shows, how GitHub API can be called using named HttpClient instance. A base address and request headers are configured for the named instance.
Next, when the IHttpClientFactory is injected in any class, the name of the instance can be passed to CreateClient method to get HttpClient instance, with all the the intended settings.
I think this method may prove useful in some situations. It might reduce some duplication of code. Also, all required http communication can be configured at a single place using the http client middleware.
The only thing that might not be ideal is – use of string- for specifying name and for getting the instance of HttpClient. But, a constant can be used to make sure there are no runtime errors due to spelling mistakes / variations.
Are you going to use this in any of your project ? Let me know your thoughts.
This Post Has One Comment
Great post. I needed an example of a named client implementation (vs. the typed client implementation seen at https://docs.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests ) and this is it. Now that I can see both of these options, the named client implementation is obviously correct for me since I’m dealing with ~10 external APIs which need to have their base options configured differently.