liveBook · Manning

HTTP client

As explained in ASP.NET Core in Action, 3e

HttpClient is the .NET class for sending HTTP requests and receiving HTTP responses.

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

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains requests, responses, handler pipelines, socket exhaustion, DNS rotation, and factory-based lifetime management.
Examples
Uses a minimal API calling an example rates endpoint with GetAsync, EnsureSuccessStatusCode, and ReadAsStringAsync.
What it assumes
Assumes basic C# familiarity while introducing HTTP API consumption and its lifecycle pitfalls.
What you can do after
Apply it via HttpClient to send requests, read responses, and choose safer lifetime management with IHttpClientFactory.
How it connects
Connects HTTP APIs with IHttpClientFactory, HttpMessageHandler, DNS, socket exhaustion, named clients, typed clients, and Polly.

Also explained in

Compare how 4 books explain HTTP client →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.