Unable to read data from the transport connection : An existing connection was forcibly closed by the remote host

I received this error when calling a web-service. The issue was also related to transport level security. I could call the web-service through a website project, but when reusing the same code in a test project I would get a WebException that contained this message. Adding the following line before making the call resolved the issue:

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

Edit

System.Net.ServicePointManager.SecurityProtocol - This property selects the version of the Secure Sockets Layer (SSL) or Transport Layer Security (TLS) protocol to use for new connections that use the Secure Hypertext Transfer Protocol (HTTPS) scheme only; existing connections are not changed.

I believe the SecurityProtocol configuration is important during the TLS handshake when selecting the protocol version.

TLS handshake - This protocol is used to exchange all the information required by both sides for the exchange of the actual application data by TLS.

ClientHello - A client sends a ClientHello message specifying the highest TLS protocol version it supports ...

ServerHello - The server responds with a ServerHello message, containing the chosen protocol version ... The chosen protocol version should be the highest that both the client and server support. For example, if the client supports TLS version 1.1 and the server supports version 1.2, version 1.1 should be selected; version 1.2 should not be selected.


This error usually means that the target machine is running, but the service that you're trying to connect to is not available. (Either it stopped, crashed, or is busy with another request.)

In English: The connection to the machine (remote host/server/PC that the service runs at) was made but since the service was not available on that machine, the machine didn't know what to do with the request.

If the connection to the machine was not available, you'd see a different error. I forget what it is, but it's along the lines of "Service Unreachable" or "Unavailable".

Edit - added

It IS possible that this is being caused by a firewall blocking the port, but given that you say it's intermittent ("sometimes when the client tries to connect"), that's very unlikely. I didn't include that originally because I had ruled it out mentally before replying.


My specific case scenario was that the Azure app service had the minimum TLS version changed to 1.2

I don't know if that's the default from now on, but changing it back to 1.0 made it work.

You can access the setting inside "SSL Settings".