c# - 尝试从 Azure Web 应用程序联系外部 Web 服务时出现间歇性 SocketException
问题描述
我遇到了难以调试的生产情况。
有时无法建立与外部服务的连接,并出现以下错误:
System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 93.39.196.220:443
at System.Net.Sockets.Socket.InternalEndConnect(IAsyncResult asyncResult)
at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.EndGetRequestStream(IAsyncResult asyncResult, TransportContext& context)
at System.Net.Http.HttpClientHandler.GetRequestStreamCallback(IAsyncResult ar)
--- End of inner exception stack trace ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
有时它可以正常工作。这是我尝试过的:
- 替换我执行连接的方式(从 Restsharp 到 HttpClient)
- 正如这篇文章所建议的那样,HttpClient 很长寿
- 调整超时
- 使用异步和同步代码
- 分析 SNAT 端口耗尽
更多信息:
- 我的服务器的 IP 由外部服务授权(如果不是,我将收到不同的错误)
- 在生产过程中,我遇到了问题,我可以从开发或登台连接到服务(因此外部服务不应该有问题)
- 虽然我在联系此服务时遇到问题,但我在联系其他(但类似)服务时没有问题
- 我在 Azure 上的 Web 应用服务上。我正在使用 .NET 框架 4.7.2
- 相同的代码有时有效,有时无效
这是(或多或少)当前迭代
private async Task<ResultSet> SendRequestAsync(HttpClient client, RateRequestBody document){
ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;
var response = await client.PostAsXmlAsync(baseUrl + "/XMLServices", document);
if (response.IsSuccessStatusCode){
...
}else{
...
}
}
关于我可能错过的任何想法?谢谢
解决方案
答案可能在这里:.NET 4.5 中的默认安全协议
假设两台服务器都正常运行,一个与您的客户端代码一起工作正常,另一台根据您的“更多信息”部分给您带来问题:“虽然我无法联系此服务,但联系不同的服务没有问题(但类似)服务”
我建议删除或注释掉以下行并尝试一下:
//ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;
...或将其替换为:
ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
推荐阅读
- r - 如果我在 r 中有超过 50 个值,我应该使用什么来代替嵌套的 ifelse?
- opentsdb - OpenTSDB 指标列表
- typescript - Typescript - 具有映射类型的模拟接口
- c# - MVVM - 从 ViewModel 访问视图中的 xaml 元素
- python - Pandas:将列中的列表拆分为多行
- python - 使用 Python 编码文本文件
- java - 在 Soot 中创建的类对象的输出类文件
- python - Networkx,用最短路径做最短周期
- java - 如何在 Android exoplayer 中播放原始 NAL 单元?
- mongodb - 从 mongodb 中的嵌套文档中获取数据 / 查找不起作用