Named HTTPClient using IHttpClientFactory in ASP.NET Core

Create Named HTTPClient using IHttpClientFactory in ASPNET Core

In today’s post, we will see how to Create a Named HTTPClient using HttpClientFactory in ASP.NET Core applications.

Today in this article, we will cover below aspects,

In our last article, we understood the Differences between HTTPClient and HTTPClientFactory and also learned the Best practices to use HTTPClientFactory to create an HTTPClient object as it addresses the known issues related to HTTPClient usage in the traditional way in ASP.NET Core.

If interested Basic HTTPClient and Typed client approaches are discussed in below post,

Create a Named HTTPClient

Create an ASP.NET Core Project

Create Named HTTPClient using IHttpClientFactory in ASPNET Core

Let’s look step by step to understand and create a named HTTPClient approach where we shall be creating an HTTPClient request object using HTTPClientFactory.

Add HTTP services to the container – AddHttpClient

Please update the ConfigureServices method in Startup.cs as below,

Here in the below example, we are creating two types of Named clients i.e

  • AccountClient – This client is configured for AccountSpecific request and accept ‘application/json‘ as Content-type

  • PayBillClient – This client is configured for Payment and Bill request and accept ‘application/xml‘ as Content-type. It also configured with security using the BasicAuthentication scheme.

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddHttpClient("AccountClient", c =>
            {
                c.BaseAddress = new Uri(Configuration.GetValue<string>("AccountURL"));
                // Account API ContentType
                c.DefaultRequestHeaders.Add("Accept", "application/json");
            });
            services.AddHttpClient("PayBillClient", c =>
            {
                c.BaseAddress = new Uri(Configuration.GetValue<string>("PayBillURL"));
                // Account API ContentType
                c.DefaultRequestHeaders.Add("Accept", "application/xml");
            });
        }

Dependency injection of named HTTPClientFactory 

Interface IHTTPClientFactory  can be injected in Controller or any other class as needed using Constructor injection as below,

Below shows an example purpose only where we are using Controller constructor injection,

Create Named HTTPClient using IHttpClientFactory in ASPNET Core

Add using namespace ‘System.Net.Http’ in the code to access HTTPClient and IHTTPClientFactory 

Below is the client-side code base for the named HTTPClient.

Here we specify the name of the HTTPClient request using an overloaded method CreateClient(“client name”).

        [HttpGet]
        public async Task<IActionResult> OnGet()
        {
            var client = _clientFactory.CreateClient("AccountClient");
            var response = await client.GetAsync(uri);
            if (response.IsSuccessStatusCode)
            {
                return Ok(response.Content.ReadAsStreamAsync().Result);
            }
            else
            {
                return StatusCode(500, "Something Went Wrong! Error Occured");
            }
        }

Similarly, another named HTTPClient for “PayBillClient” can be created as below,

  var client = _clientFactory.CreateClient("PayBillClient");

As we understood above HTTPClientFactory lets you DI inject the HTTPClient objects using an explicit Dependency Injection principle(DI).

This technique can be used configure multiple HTTPClients request with custom configuration of Policy, Security and delegates as required.

This technique lets you control the lifetime management of HTTPClient instances through the API pipeline itself.

With this technique, we are able to centralize multiple clients with specific configurations like using network credentials, specific headers, or security tokens as needed.

References:

Summary

In this article, we looked at how to use HTTPClientFactory for creating a Named HTTPClient request object to invoke HTTP services in ASP.NET Core. This technique also lets you control custom clients based on the required policy and delegates.



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



Leave a Reply

Your email address will not be published. Required fields are marked *