As the most voted answer by @LukeDuff correctly says, it is probable that the server uses an invalid or untrusted (or self-signed, what is technically also untrusted) certificate. But the answer blindly accepts any certificate. And what's worse, even any certificate for any site, even for sites, where you expect trusted and valid certificate. That's a security flaw.
When implementing ServicePointManager.ServerCertificateValidation
callback one should validate the certificate. E.g. by checking certificate's hash against a known value:
using System.Net;
using System.Net.Security;
using System.Security.Cryptography;
ServicePointManager.ServerCertificateValidationCallback +=
(sender, certificate, chain, errors) =>
{
return
(errors == SslPolicyErrors.None) ||
certificate.GetCertHashString(HashAlgorithmName.SHA256).Equals(
"EB8E0B28AE064ED58CBED9DAEB46CFEB3BD7ECA677...");
};
For the X509Certificate.GetCertHashString
overload that takes HashAlgorithmName.SHA256
, you need .NET 4.8. On older versions use the parameter-less overload that returns an SHA-1 hash.
Based on Is it safe to test the X509Certificate.Thumbprint property when you know an invalid certificate is safe?
For VB.NET version of the code, see Accept self-signed TLS/SSL certificate in VB.NET.