In today’s post, we will see how to create named HTTPClient requests using HTTPClientFactory in .NET Core or ASP.NET Core.

Create a Named HTTPClient

Create an ASP.NET Core Project

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

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

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

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

Here in below example, we are creating two types of Named client,

  • 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");
           });
       }

Below is the client-side code base for 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 uri = new Uri("https://localhost:44364/account");
            var client = _clientFactory.CreateClient("AccountClient");
            var response = await client.GetAsync(uri);
            if (response.IsSuccessStatusCode)
            {
                return Ok(response.Content.ReadAsStreamAsync().Result);
            }
            else
            {
                return StatusCode(500, "Somthing Went Wrong! Error Occured");
            }
        }

Similarly, other 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.

That’s All, Happy coding !!. Please sound off your comments below.

Summary

In this article, we looked at how to use HTTPClientFactory for creating 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.

Leave a comment

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