ASP.NET Tutorial : Optimize HttpClient Usage in .NET Core

Leave a Comment

Class HttpClient
System.Net's HttpClient class.HTTP/HTTPS makes it easier to send and receive HTTP requests and answers from resources denoted by URIs. Every instance of a HttpClient encapsulates a set of settings that are applied globally to every request it processes, and each instance has its own connection pool to guarantee request isolation. The underlying implementation is provided by the SocketsHttpHandler class, which is available starting with.NET Core 2.1 and guarantees consistent behavior across many platforms.

HttpClient can be implemented in two ways in an app, and it is advised to select the implementation that best suits the client's lifetime management requirements.


  • For enduring customers: Using the HttpClient class, create a static or singleton instance and set PooledConnectionLifetime.
  • For transient clients: Utilize the IHttpClientFactory-created clients.

Long-Lived Client

DNS entries are only resolved by HttpClient upon connection establishment. Time to live (TTL) durations set by the DNS server are not tracked by it. The client won't be informed of updates if DNS entries change frequently. By configuring the PooledConnectionLifetime property to require a DNS query upon connection replacement, you can circumvent this problem by limiting the connection's duration.

HttpClient is set up in the example below to reuse connections for a duration of five minutes. The connection is ended and a new one is established when the TimeSpan given by PooledConnectionLifetime has passed.

var handler = new SocketsHttpHandler
{
    PooledConnectionLifetime = TimeSpan.FromMinutes(5) // Recreate every 5 minutes
};
var client = new HttpClient(handler);
Pooled connections

The HttpClient's connection pool is tied to its underlying SocketsHttpHandler. The HttpClient also disposes of all existing connections in the pool. Consequently, subsequent requests to the same server necessitate new connection creation, incurring a performance penalty due to unnecessary connection overhead. Additionally, TCP ports aren't immediately released upon closure, potentially leading to port exhaustion, especially under high request rates. To mitigate port exhaustion issues, it's advisable to reuse HttpClient instances for multiple HTTP requests whenever feasible.

Short-Lived Client

The IHttpClientFactory acts as a factory abstraction enabling the creation of HttpClient instances with tailored configurations, introduced in .NET Core 2.1. It simplifies the integration of third-party middleware for common HTTP-based .NET workloads. By utilizing the AddHttpClient extension methods, the IHttpClientFactory and associated services are seamlessly added to the IServiceCollection.

Pooled connections

The HttpClient's connection pool is tied to its underlying SocketsHttpHandler. The HttpClient also disposes of all existing connections in the pool. Consequently, subsequent requests to the same server necessitate new connection creation, incurring a performance penalty due to unnecessary connection overhead. Additionally, TCP ports aren't immediately released upon closure, potentially leading to port exhaustion, especially under high request rates. To mitigate port exhaustion issues, it's advisable to reuse HttpClient instances for multiple HTTP requests whenever feasible.

Short-Lived Client

The IHttpClientFactory acts as a factory abstraction enabling the creation of HttpClient instances with tailored configurations, introduced in .NET Core 2.1. It simplifies the integration of third-party middleware for common HTTP-based .NET workloads. By utilizing the AddHttpClient extension methods, the IHttpClientFactory and associated services are seamlessly added to the IServiceCollection.

IHttpClientFactory Implementations

With modern application development principles driving best practices, the IHttpClientFactory serve is a factory abstraction that can create HttpClientinstances with custom configurations.IHttpClientFactory was introduced in .NET Core 2.1. Common HTTP-based .NET workloads can take advantage of resilient and transient-fault-handling third-party middleware with ease.

In Startup DI

HostApplicationBuilder builder = Host.CreateApplicationBuilder(args);

builder.Services.AddHttpClient();

Usage

using HttpClient client = httpClientFactory.CreateClient();
Consumption patterns

There are several ways iHttpClientFactory can be used in an app.

  • Basic usage
  • Named clients
  • Typed clients
  • Generated clients

We will see two patterns here:

Basic usage

Adding HttpClientFactory registration is accomplished by invoking AddHttpClient.

In Startup DI

HostApplicationBuilder builder = Host.CreateApplicationBuilder(args);

builder.Services.AddHttpClient();

Usage

using HttpClient client = httpClientFactory.CreateClient();
Named clients

Named clients are advantageous when an application necessitates numerous unique implementations of HttpClient, with each HttpClient instance requiring different configurations. These configurations for a named HttpClient can be specified during registration on the IServiceCollection.

builder.Services.AddHttpClient("ActionHttpClientName",

client => {

 client.BaseAddress = new Uri("https://api.sample.com/");

 client.DefaultRequestHeaders.Add("apikey", "LOKU#(SHHHH773");

});

In the above code, the client is configured with

  • A name that's "ActionHttpClientName".
  • The base addresshttps://api.sample.com/
  • Added the apiKey for authentication purposes.

Usage

using HttpClient client = _httpClientFactory.CreateClient("ActionHttpClientName");
HttpClientlifetime management

A new HttpClient instance is returned each timeCreateClientis called on theIHttpClientFactory. One HttpClientHandler instance is created per client name. The factory manages the lifetimes of theHttpClientHandlerinstances. IHttpClientFactorycaches theHttpClientHandlerinstances created by the factory to reduce resource consumption. AnHttpClientHandlerinstance may be reused from the cache when creating a newHttpClientinstance if its lifetime hasn't expired. Caching handlers is desirable as each handler typically manages its own underlying HTTP connection pool. Creating more handlers than necessary can result in socket exhaustion and connection delays. Some handlers also keep connections open indefinitely, which can prevent the handler from reacting to DNS changes.

Windows Hosting Recommendation

HostForLIFEASP.NET receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2022 R2, SQL Server 2022, ASP.NET Core 7.0.10 , ASP.NET MVC, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/
Next PostNewer Post Previous PostOlder Post Home

0 comments:

Post a Comment