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 ;
         }
     }
 };
 

Setting Request timeout interval in WebClient (C#)

Most programmers who work with remote HTTP services prefer to use WebClient over WebRequest/WebResponse because of its simplicity. The only WebClient's feature I missed is ability to customize request timeout interval but fortunatelly it is very easy to fix by creating own class derived from WebClient. Here is how....

 public  class  WebClientEx  : WebClient
  {
     // Timeout in milliseconds
      public  int  Timeout { get ; set ; }
 
     /// <summary>
      /// Sets default timeout
      /// </summary>
      public  WebClientEx()
         : base ()
     {
         this .Timeout = 10000;
     }
 
     /// <summary>
      /// Sets custom timeout
      /// </summary>
      /// <param name="timeout">Timeout in milliseconds</param>
      public  WebClientEx(int  timeout)
         : base ()
     {
         this .Timeout = timeout;
     }
 
     /// <summary>
      /// Overriding base method to set timeout
      /// </summary>
      /// <param name="address">Server Url</param>
      /// <returns>A WebRequest with a timeout assigned</returns>
      protected  override  WebRequest  GetWebRequest(Uri  address)
     {
         WebRequest  wr = base .GetWebRequest(address);
         wr.Timeout = this .Timeout;
         return  wr;
     }
 }