System.Net.Http.HttpRequestException: No connection could be made because the target machine actively refused it.
ID: dotnet/httprequestexception
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 8 | active | — | — | — |
Root Cause
HttpRequestException is thrown when an HTTP request fails at the transport level. Common causes include unreachable endpoints, DNS resolution failures, SSL/TLS errors, and socket exhaustion from not using IHttpClientFactory. Fix by verifying connectivity, using IHttpClientFactory, and adding retry policies.
genericWorkarounds
-
90% success Use IHttpClientFactory for proper connection pool management
Register in DI: builder.Services.AddHttpClient<MyService>(client => { client.BaseAddress = new Uri("https://api.example.com"); }); Then inject IHttpClientFactory or the typed client. This manages DNS changes, connection pooling, and socket lifecycle automatically -
85% success Add Polly retry policies for transient failures
Install Microsoft.Extensions.Http.Polly and configure: builder.Services.AddHttpClient<MyService>().AddTransientHttpErrorPolicy(p => p.WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)))). This handles transient network errors with exponential backoff
Dead Ends
Common approaches that don't work:
-
Creating new HttpClient instances per request instead of using IHttpClientFactory
75% fail
Each HttpClient instance holds its own connection pool and socket. Creating many instances leads to socket exhaustion (TIME_WAIT state), causing subsequent requests to fail with HttpRequestException
-
Disabling SSL certificate validation to fix SSL/TLS errors
70% fail
Bypasses security entirely, making the application vulnerable to man-in-the-middle attacks. The SSL error usually indicates a legitimate certificate configuration problem that should be properly fixed