In one of my project, I was trying to call third party API through HttpWebRequest POST method by passing the certificate like below.
static void Main(string[] args) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://thirdpartapi/"); request.Method = "POST"; X509Store store = new X509Store(StoreName.TrustedPeople, StoreLocation.LocalMachine); X509Certificate2Collection localCerts = store.Certificates.Find(X509FindType.FindByThumbprint, "dfeecb64f3332f3eb4f3746bf49508bd7b577903", true); request.ClientCertificates.Add(localCerts[0]); WebResponse respon = request.GetResponse(); Stream res = respon.GetResponseStream(); }
But getting the error as "The request was aborted: Could not create SSL/TLS secure channel in C#". After a lot of research, we found that we get this error if we use the .Net Framework 4.5 or less where we have to enable security protocol version through code before declaring the object for HttpWebRequest as shown below.
static void Main(string[] args) { ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3; HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://thirdpartapi/"); request.Method = "POST"; X509Store store = new X509Store(StoreName.TrustedPeople, StoreLocation.LocalMachine); X509Certificate2Collection localCerts = store.Certificates.Find(X509FindType.FindByThumbprint, "dfeecb64f3332f3eb4f3746bf49508bd7b577903", true); request.ClientCertificates.Add(localCerts[0]); WebResponse respon = request.GetResponse(); Stream res = respon.GetResponseStream(); }
So, to resolve the "The request was aborted: Could not create SSL/TLS secure channel", we have to add below code before declaring the HttpWebRequest object.
ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;
If you use .Net Framework 4.6 or higher, we don't require to declare above security settings in the code.