Two major issues with standard HttpClient usage in .NET:
- Socket Exhaustion: Creating
new HttpClient()per request leaves hundreds of sockets inTIME_WAITstate, starving OS network ports. - Stale DNS: Storing a singleton
static HttpClientcaches DNS indefinitely, failing when IP addresses rotate during cloud deployments.
The Fix:
Register with services.AddHttpClient() and inject IHttpClientFactory:
public class WeatherService(HttpClient client)
{
public async Task<string> GetForecastAsync() => await client.GetStringAsync("/forecast");
}IHttpClientFactory pools the underlying HttpMessageHandler lifetimes (default 2 minutes), rotating connections to honor DNS TTL while pooling active sockets!