Ignorar el certificado al momento de una petición a un API en C# .Net

Algunas veces necesitamos ignorar los certificados cuando nos conectamos a un API la cual pide SSL por ejemplo y necesitamos hacer pruebas, para ello podemos hacer el siguiente truco, agregamos el siguiente método (AceptarTodosLosCertificados) en nuestra clase:

1
2
3
4
5
6
7
8
class Conexion{
 
        public bool AceptarTodosLosCertificados(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }
 
}

Y ya solo invocamos la siguiente línea antes de hacer la petición a la API:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Conexion{
 
        public bool AceptarTodosLosCertificados(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }
 
       public bool Connect(){
 
            try
            {
 
                //linea donde invocamos el metodo
                ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AceptarTodosLosCertificados);
 
                //aquí el codigo para la petición
 
                var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://www.paginaconseguridad.com/lalala");
                httpWebRequest.ContentType = "application/json; charset=utf-8";
                httpWebRequest.Method = "POST";
                httpWebRequest.Accept = "application/json";
 
                //y aqui mas codigo .....
 
                return true;
            }catch(Exception ex){
                error = ex.Message;
                return false;
            }
 
        }
 
}

Así de sencillo nos brincaremos el certificado.