dotnet network_error ai_generated true

System.Net.Http.HttpRequestException: 无法建立连接,因为目标计算机主动拒绝连接。SocketException: 无法建立连接,因为目标计算机主动拒绝连接。(127.0.0.1:443)

System.Net.Http.HttpRequestException: No connection could be made because the target machine actively refused it. SocketException: No connection could be made because the target machine actively refused it. (127.0.0.1:443)

ID: dotnet/httpclient-socket-connection-pool-exhausted

其他格式: JSON · Markdown 中文 · English
90%修复率
86%置信度
1证据数
2023-06-20首次发现

版本兼容性

版本状态引入弃用备注
.NET Core 3.1 active
.NET 5.0 active
.NET 6.0 active
.NET 7.0 active
.NET 8.0 active

根因分析

HttpClient 实例未正确释放,导致套接字耗尽和端口枯竭,每个实例在并发高的情况下长时间占用 TCP 连接。

English

HttpClient instances are not being disposed properly, leading to socket exhaustion and port starvation as each instance holds onto TCP connections for longer than necessary, especially under high concurrency.

generic

官方文档

https://learn.microsoft.com/en-us/dotnet/fundamentals/networking/http/httpclient-guidelines

解决方案

  1. Use IHttpClientFactory to manage HttpClient instances. Register it in DI: services.AddHttpClient(); Then inject IHttpClientFactory and create clients with factory.CreateClient(). This reuses connections and avoids socket exhaustion.
  2. If not using DI, use a static or singleton HttpClient instance and ensure it is not disposed. Example: private static readonly HttpClient _httpClient = new HttpClient();
  3. Increase the default connection limit per remote endpoint using ServicePointManager: ServicePointManager.DefaultConnectionLimit = 100; Place this in application startup.

无效尝试

常见但无效的做法:

  1. Creating a new HttpClient instance for each request inside a using block. 90% 失败

    Disposing HttpClient too frequently causes socket exhaustion because each instance opens a new TCP connection but does not reuse sockets efficiently.

  2. Increasing the connection limit in the app.config or machine.config. 70% 失败

    While this can help, it does not address the root cause of not reusing connections; it only delays exhaustion.

  3. Setting ServicePointManager.DefaultConnectionLimit to a high value. 80% 失败

    This is a global setting that affects all HttpClient instances and may not be sufficient if instances are created and disposed frequently.