Zayko in the Net

Personal blog of Vitaly Zayko

NAVIGATION - SEARCH

How to bypass self-signed SSL certificate exception? (C#)

When you try to connect your client App to a server through self-signed SSL certificate (which is normal during development, but obviously is not in production), by default you will get a security exception because such certificate could not be validated. The good approach is to warn user and let him choose whatever he wants to take this risk or not. Add the following code to your class/form to give him such choise. The good idea is to store his response in a local variable and use it to skip this warning in future requests.

 ServicePointManager .ServerCertificateValidationCallback = (s, cert, ch, er) =>
 {
     // Check is this case has been valuated:
      if  (Program .IsCertVerified)
         return  true ;
 
     if  (er == System.Net.Security.SslPolicyErrors .None)
         return  true ;
     else
      {
         // Warn user:
          if  (MessageBox .Show(String .Format("Certificate \\"{0}\\" could not be verified! Do you want to continue?" ,
             cert.Subject), "Certificate Warning" ,
             MessageBoxButtons .YesNo, MessageBoxIcon .Warning) == System.Windows.Forms.DialogResult .Yes)
         {
             // Set the local variable to skip this dialog:
              Program .IsCertVerified = true ;
             return  true ;
         }
         else
          {
             Program .IsCertVerified = false ;
             return  false ;
         }
     }
 };
 

Add comment