I'm encountering a situation on production that is difficult to debug.
Sometimes the connection to an external service can't be established with the following error:
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)
Sometimes it works without any problem. This is what I've tried:
- Replacing the way I perform the connection (from Restsharp to HttpClient)
- HttpClient is long lived as suggested by this post
- Adjusting the timeout
- Using async and sync code
- Analyzing SNAT Port exhaustion
More info:
- The IPs of my server are authorized by the external service (and if they weren't I would be receiving a different error)
- While on production I'm having the problem I'm able to connect to the service from development or staging (so it shouldn't be a problem with the external service)
- While I'm having trouble contacting this service I don't have trouble contacting a different (but similar) service
- I'm on a Web App Service on Azure. I'm using the .NET framework 4.7.2
- The same code sometimes works and sometimes it doesn't
This is (more or less) the current iteration
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{
...
}
}
Any ideas on what I might have missed? Thanks