C# and .NET • Modern C# baseline
HTTP APIs and HttpClient Lifetime
Send HTTP requests asynchronously and manage client lifetime with the hosting model.
HttpClient owns connection-pooling behavior and should not be created and disposed for every request. In hosted applications, IHttpClientFactory provides named or typed clients with centralized configuration and handler lifetime management. Check response status and validate the response body before using it.
Key points
- Use cancellation tokens for network operations.
- Set timeouts and avoid logging credentials or sensitive response bodies.
Example
using System.Net.Http;
static async Task<string> GetTextAsync(
HttpClient client,
Uri address,
CancellationToken cancellationToken)
{
using var response = await client.GetAsync(address, cancellationToken);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync(cancellationToken);
}
What to expect
Returns the response body for a successful status and throws for an unsuccessful status.
Practice exercise
Add handling for expected 404 responses and decide whether they should become a domain-level “not found” result.
Key idea: Treat network status, timeouts, cancellation, and payload validation as distinct outcomes.