How to solve SSL/TLS validation error while making connection in C#

In this article, you will learn how to deal with SSL/TLS validation error using C#. If you are trying to establish a connection with a web server using c# and getting an exception as given below :

  • SocketException: An existing connection was forcibly closed by the remote host
  • IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
  • WebException: The underlying connection was closed: An unexpected error occurred on a send.
  • HttpRequestException: An error occurred while sending the request.

There might be chances that URL you are trying to hit in order to get make a connection is either not accessible or having not secure SSL issues. Please have a look at the given picture when I figure out what error I am getting in the browser after not able to make a connection.

Below code, I’ve used to make a connection where I met with exceptions.

While the same code was working fine to make a connection with another web service, so just to figure out I tried to browse the same URL on the browser. Please have a look at the given picture when I figure out what error I am getting in the browser after not able to make a connection.

NET::ERR_CERT_COMMON_NAME_INVALID  

If you are also getting the same error listed above and having the same issue while browsing URL in the browser, you can simply solve it bypassing SSL error. You can use below code

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; 
ServicePointManager.ServerCertificateValidationCallback +=(sender, cert, chain, sslPolicyErrors) => { return true; };
Note: If you are using .Net Framework 4.0
Use
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
Instead of ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

The complete code will look like as given below

About Ravi Ranjan Kumar 32 Articles
An Indian who Living, Loving & Learning Technology with different tastes and willing to share knowledge and thoughts.

Be the first to comment

Leave a Reply