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
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| .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.
官方文档
https://learn.microsoft.com/en-us/dotnet/fundamentals/networking/http/httpclient-guidelines解决方案
-
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.
-
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();
-
Increase the default connection limit per remote endpoint using ServicePointManager: ServicePointManager.DefaultConnectionLimit = 100; Place this in application startup.
无效尝试
常见但无效的做法:
-
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.
-
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.
-
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.