Post for HttpClient named instance
Post for HttpClient named instance

Named Http Clients In .NET Core Web Applications

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.

Why ?

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.

How ?

AddHttpClient provides a way to centralize all the HTTP client configurations at one place. Named clients are a good choice when:

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.

Leave a ReplyCancel reply

This Post Has One Comment

  1. qwerty0003

    Great post. I needed an example of a named client implementation (vs. the typed client implementation seen at ) 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.