使用HttpClient调用服务时遭遇SocketException(0x274c)问题求助
Hey there, let's break down this SocketException (0x274c) you're encountering—this error code maps to WSAECONNRESET, which means the connection was reset by the remote server or hit a local connection limit issue. Here are the most common fixes and troubleshooting steps to resolve this:
1. Fix HttpClient Instance Management (Most Likely Culprit)
Your current code creates a new HttpClient instance every time SendRequestToTheService runs using using. While this seems correct at first glance, HttpClient is designed to be reused as a singleton—recreating it repeatedly exhausts the underlying socket connection pool, leading to TIME_WAIT connections piling up and eventually hitting port limits.
Optimized Code Example (Singleton HttpClient):
// Create a static, reusable HttpClient instance (one per application) private static readonly HttpClient _client = new HttpClient(); // Initialize settings in a static constructor static YourClassName() { _client.BaseAddress = new Uri(baseUrl); _client.Timeout = TimeSpan.FromSeconds(30); // Set a reasonable timeout // Increase connection limit for your target service ServicePointManager.FindServicePoint(new Uri(baseUrl)).ConnectionLimit = 10; } private async Task<Data> SendRequestToTheService(string searchTerm) { Response response = new Response(); await Step1(param1, _client); await Step2(param1, param2, _client); response = await Step3(param, _client); return response; }
If you're using .NET Core/.NET 5+, IHttpClientFactory is even better—it handles connection pooling and instance management automatically:
// Inject IHttpClientFactory via constructor private readonly IHttpClientFactory _httpClientFactory; public YourClassName(IHttpClientFactory httpClientFactory) { _httpClientFactory = httpClientFactory; } private async Task<Data> SendRequestToTheService(string searchTerm) { var client = _httpClientFactory.CreateClient(); client.BaseAddress = new Uri(baseUrl); client.Timeout = TimeSpan.FromSeconds(30); Response response = new Response(); await Step1(param1, client); await Step2(param1, param2, client); response = await Step3(param, client); return response; }
2. Check Connection Limits
By default, .NET limits concurrent connections to the same server to 2. If your steps are running in parallel (or even sequential calls pile up), this can cause timeouts and connection resets. Adjust the limit for your target service:
// Set global limit (not recommended if you call multiple services) ServicePointManager.DefaultConnectionLimit = int.MaxValue; // Or set limit only for your specific base URL ServicePointManager.FindServicePoint(new Uri(baseUrl)).ConnectionLimit = 10;
3. Validate Request/Response Handling
- Ensure your
Step1,Step2,Step3methods are properly disposing ofHttpContentobjects (if usingStringContent,JsonContent, etc.). Unmanaged content can leak connections. - Check if your requests are malformed (e.g., incorrect
Content-Type, invalid JSON payloads). A server may reset the connection if it can't parse your request. - Add timeout handling: If the server takes too long to respond, the connection may be reset. Set a explicit timeout on the
HttpClientas shown in the code examples above.
4. Investigate Server-Side Issues
The reset could be initiated by the remote service:
- Does the service have rate limiting or request throttling enabled? Your 3 sequential calls might be hitting a limit.
- Check the service's logs for errors related to your requests—maybe it's crashing or rejecting connections under load.
- Use a tool like Wireshark to capture network traffic and see exactly when the connection reset happens (is it during request send, waiting for response, etc.?).
内容的提问来源于stack exchange,提问作者arslanaybars

