【问题标题】:Getting "System.Net.WebException: The underlying connection was closed: The connection was closed unexpectedly." error while calling web api获取“System.Net.WebException:底层连接已关闭:连接意外关闭。”调用 web api 时出错
【发布时间】:2022-01-19 15:10:33
【问题描述】:

在我的应用程序中,有一个功能可以根据日期范围提取报告。在后台,它使用身份验证(A)调用我的 Web API,它由使用 httpclient 的 api 调用程序功能组成,它调用另一个非安全 DMZ 服务器 API(B)和一个 DMZ API 校准 WCF 服务(C)从数据库中收集数据。 我的问题是,每当我选择较大的日期范围时,我的 WebAPI (A) 中都会出现以下错误。

System.Net.Http.HttpRequestException:发送请求时出错。 ---> System.Net.WebException:底层连接已关闭:连接意外关闭。 在 System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult) 在 System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar) --- 内部异常堆栈跟踪结束 --- 在 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务) 在 System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(任务任务) 在 System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() 在 LRAS.OrderServices.Core.Helpers.ApiCaller.d__4.MoveNext()

我的尝试:我已将 httpclient 超时从 300 秒增加到 1000 秒,但它几乎每分钟都在中断。

【问题讨论】:

    标签: c# wcf asp.net-web-api httpclient


    【解决方案1】:

    您可以尝试几种方法:
    1.配置服务点安全协议,选择适合自己的SecurityProtocolType(Tls12、Ssl3、Tls、Tls11)。

    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
    

    C# System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send
    2.设置HttpClient的ConnectionClose属性。

    _client.DefaultRequestHeaders.ConnectionClose = true;
    

    HttpClient throwing "An error occurred while sending the request."

    3.尝试将请求保持足够长的时间以使其正常完成并接收有效响应。

    _client.DefaultRequestHeaders.Add("Connection", "Keep-Alive");
    _client.DefaultRequestHeaders.Add("Keep-Alive", "3600");
    

    .NET HttpClient - An existing connection was forcibly closed by the remote host

    【讨论】:

    猜你喜欢
    • 2010-11-30
    • 2020-06-24
    • 1970-01-01
    • 2013-05-31
    • 1970-01-01
    相关资源
    最近更新 更多