dotnet networking ai_generated true

System.Net.Http.HttpRequestException: No connection could be made because the target machine actively refused it.

ID: dotnet/httprequestexception

Also available as: JSON · Markdown
83%Fix Rate
86%Confidence
75Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
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.

generic

Workarounds

  1. 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
  2. 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:

  1. 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

  2. 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

Error Chain

Leads to:
Preceded by:
Frequently confused with: