首页 > 解决方案 > 尝试从 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)

有时它可以正常工作。这是我尝试过的:

SNAT 失败

更多信息:

这是(或多或少)当前迭代

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{
      ...
    }
}

关于我可能错过的任何想法?谢谢

标签: c#azure-web-app-servicehttpclient

解决方案


答案可能在这里:.NET 4.5 中的默认安全协议

假设两台服务器都正常运行,一个与您的客户端代码一起工作正常,另一台根据您的“更多信息”部分给您带来问题:“虽然我无法联系此服务,但联系不同的服务没有问题(但类似)服务”

我建议删除或注释掉以下行并尝试一下:

//ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;

...或将其替换为:

ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

推荐阅读