Solved: Exception System.Net.WebException: The request was aborted: Could not create SSL/TLS secure channel. is very frequent particularly when downloading file or JSON request when consuming API over https secure SSL connection encryption.
System.Net.WebException
This exception appear while downloading a file or data using class System.Net.WebClient
or HttpWebRequest``through `WebRequest.Create
method e.g.: `at System.Net.WebClient.DownloadFile(Uri address, String fileName) but not limited to these classes only.
Solution for .NET 4.5 or above
The solution for .NET Framework 4.5 or above is to add following line of code before sending the HTTP Request:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
Solution for earlier versions than .NET Framework 4.5
The solution for earlier versions than .NET Framework 4.5 is to add following line of code before sending the HTTP Request:
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
In case if the above solutions do not work, then add the following line of code as well:
ServicePointManager.Expect100Continue = true;
This also work for vb.net using the corresponding syntax.
Complete Code Example
Following code downloads the Wikipedia log successfully with following code.
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
using (WebClient client = new WebClient())
{
client.DownloadFile("https://en.wikipedia.org/static/images/project-logos/enwiki.png", "c:\enwiki.png");
To check the difference, comment the first two lines of code then you will receive the exception as described in the start of this article.
Posted Status in Programming