Simple Tips to Handle Multiple HttpClients in Same ASP.NET Core Application – Windows ASP.NET Core Hosting 2024 | Review and Comparison

It’s likely that your application is using numerous different methods to access the same Web Service. If so, you have the chance to centralize part of your code if you’re utilizing the HttpClientFactory, which you really ought to be.

The AddHttpClient method, which, despite its name, actually adds a HttpClientFactory to your application’s services collection, should be called in your Startup class. You can give a string and a lambda expression to the AddHttpClient method as part of that method. You can include the code to configure the HttpClient objects made by the factory in the lambda expression. You can use the string you supplied to get the configuration you specified when it’s time to build a HttpClient object.

For instance, the following code shows how the BaseAddress on the HttpClient should be defined when this factory is used and supplies the name “phvis” to the AddHttpClient method:

services.AddHttpClient("phvis", hc =>
{
    hc.BaseAddress = new Uri("https://phvis.com/");
});

Now, you can use “phvis” to get a client that is set up for my site when you go to create a HttpClient. In this code, for instance, a HttpClient configured for phvis.com is retrieved (see my earlier advise on how to do this so that you can use the factory by retrieving it from the services collection here):

var client = factory.CreateClient("phvis");

The client’s BaseAddress field is already set, thus when making a request, all that is required is the back portion of the service’s URL. This example sends a request to https://phvis.com/Customer/A123 by combining a relative URL that was supplied to the GetAsync method with my earlier BaseAddress:

var response = await Client.GetAsync("/Customer/A123");

Furthermore, nothing prevents you from creating numerous named clients, each with their BaseAddress configured for the various services you’re using, if you’re using multiple Web Services.