C# System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send

Jon picture Jon · Apr 27, 2015 · Viewed 95.8k times · Source

I'm getting this error on just one server running Windows Server 2003:

System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send.


Here's my code... Any ideas?

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https:// URL HERE ");
//request.Headers.Add("Accept", "application/xml");
byte[] bytes;
bytes = System.Text.Encoding.ASCII.GetBytes(xml);
request.KeepAlive = false;
request.Accept = "application/xml";
request.ContentType = "application/xml; charset='UTF-8'";
request.ContentLength = bytes.Length;
request.Method = "POST";
request.Timeout = 10000;
request.ServicePoint.Expect100Continue = false;

Answer

Bartho Bernsmann picture Bartho Bernsmann · May 16, 2017

Setting the HttpWebRequest.KeepAlive to false didn't work for me.

Since I was accessing a HTTPS page I had to set the Service Point Security Protocol to Tls12.

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

Notice that there are other SecurityProtocolTypes:

SecurityProtocolType.Ssl3 
SecurityProtocolType.Tls
SecurityProtocolType.Tls11

So if the Tls12 doesn't work for you, try the three remaining options.

Also notice you can set multiple protocols. This is preferable on most cases.

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

Edit: Since this is a choice of security standards it's obviously best to go with the latest (TLS 1.2 as of writing this), and not just doing what works. In fact, SSL3 has been officially prohibited from use since 2015 and TLS 1.0 and TLS 1.1 will likely be prohibited soon as well. source: @aske-b