C# HttpClient - 无法从传输连接读取数据:连接被对等方重置

问题描述 投票:0回答:1

我有一个安装在 Azure 门户中的 API,在一种方法中,我使用 httpclient 来获取位于虚拟机和 http(不是 https)中的另一个 API 的目录。

如果我在本地尝试,它总是工作正常,但是当我在 Azure 门户中使用生产版本时,只要数据不超过 1024 字节,它就可以工作,但是当响应返回超过 1024 字节时,它会发送此错误:

(System.Net.Http.HttpRequestException: An error occurred while sending the request.
    ---> System.IO.IOException: Unable to read data from the transport connection: Connection reset by peer.
    ---> System.Net.Sockets.SocketException (104): Connection reset by peer
    --- End of inner exception stack trace ---
    at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError error, CancellationToken cancellationToken)
    at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.System.Threading.Tasks.Sources.IValueTaskSource<System.Int32>.GetResult(Int16 token)
    at System.Net.Http.HttpConnection.InitialFillAsync(Boolean async)
    at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
    --- End of inner exception stack trace ---
    at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
    at System.Net.Http.HttpConnectionPool.SendWithVersionDetectionAndRetryAsync(HttpRequestMessage request, Boolean async, Boolean doRequestAuth, CancellationToken cancellationToken)
    at System.Net.Http.DiagnosticsHandler.SendAsyncCore(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
    at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
    at System.Net.Http.DecompressionHandler.SendAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
    at System.Net.Http.HttpClient.<SendAsync>g__Core|83_0(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken)
    at RestSharp.RestClient.ExecuteRequestAsync(RestRequest request, CancellationToken cancellationToken))

Azure 门户中是否缺少配置?或者在 API 代码中?或者是 API 的某些配置返回响应并且位于 http 中?

c# httpclient socketexception
1个回答
0
投票

我将冒险猜测Azure/1024字节限制可能不是你的问题的原因。 您是否使用了重新使用 HttpClient 实例的正确模式(例如,将其设为静态字段或从单例包装器中获取它),避免为每个请求创建一个新字段??

如果您只在需要时使用

new HttpClient()
,这正是您在负载下出现的一种行为,因为底层连接池耗尽了可供使用的端口。

这里有一篇文章提供了一些背景信息,但这可能使它听起来更复杂。要点是只使用类似的东西

private static HttpClient Client = new HttpClient();
    
© www.soinside.com 2019 - 2024. All rights reserved.