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

- **ID:** `dotnet/httpclient-socket-connection-pool-exhausted`
- **领域:** dotnet
- **类别:** network_error
- **验证级别:** ai_generated
- **修复率:** 90%

## 根因

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

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| .NET Core 3.1 | active | — | — |
| .NET 5.0 | active | — | — |
| .NET 6.0 | active | — | — |
| .NET 7.0 | active | — | — |
| .NET 8.0 | active | — | — |

## 解决方案

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

## 无效尝试

- **Creating a new HttpClient instance for each request inside a using block.** — Disposing HttpClient too frequently causes socket exhaustion because each instance opens a new TCP connection but does not reuse sockets efficiently. (90% 失败率)
- **Increasing the connection limit in the app.config or machine.config.** — While this can help, it does not address the root cause of not reusing connections; it only delays exhaustion. (70% 失败率)
- **Setting ServicePointManager.DefaultConnectionLimit to a high value.** — This is a global setting that affects all HttpClient instances and may not be sufficient if instances are created and disposed frequently. (80% 失败率)
