HttpClient sends HTTP requests to remote APIs and reads the response headers and data. Configure the request with its headers and body, then inspect or process the returned response. section 33.5 section 33.1
Use HttpClient with lifecycle management in mind:
- Avoid creating and disposing an instance for every request; repeated disposal can cause socket exhaustion while closed sockets remain in TIME_WAIT. section 33.1 section 33.5
- A singleton instance avoids socket exhaustion but may continue using an old server address after DNS changes. section 33.1 section 33.5
- Prefer IHttpClientFactory when the application needs managed handler lifetimes, centralized configuration, named clients, typed clients, or outgoing middleware pipelines. section 33.2 section 33.5
Listing 33.1 The incorrect way to use HttpClient
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
WebApplication app = builder.Build();
app.MapGet("/", async () =>
{
using HttpClient client = new HttpClient(); #1
client.BaseAddress = new Uri("https://example.com/rates/"); #2
var response = await client.GetAsync("latest"); #3
response.EnsureSuccessStatusCode(); #4
return await response.Content.ReadAsStringAsync(); #5
});
app.Run();
The runnable example shows the tempting per-request pattern: create HttpClient, set BaseAddress, call GetAsync, ensure success, and read the response. Its disposal pattern is the problem to avoid. section 33.1



