Just Code‎ > ‎

C# - Work around for “The remote certificate is invalid according to the validation procedure"

posted Jul 13, 2012, 4:15 AM by Peter Henell   [ updated Jul 13, 2012, 4:15 AM ]
If you are working with some WebRequest towards a server that is using SSL, but the certificate on that server is not valid for some reason (it is common to generate a certificate for yourself for development environments) then you will get this Exception.
You might have code like this:
private string HttpPost(string URI, string parameters)
        {
            try
            {
                System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
                req.ContentType = "application/x-www-form-urlencoded";
                req.Method = "POST";

                byte[] bytes = System.Text.Encoding.ASCII.GetBytes(parameters);
                req.ContentLength = bytes.Length;

                using (System.IO.Stream os = req.GetRequestStream())
                {
                    // POST!!
                    os.Write(bytes, 0, bytes.Length);

                    System.Net.WebResponse resp = req.GetResponse();

                    if (resp == null)
                        return null;

                    using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream()))
                    {
                        return sr.ReadToEnd();
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                return e.ToString();
            }
        }
To avoid getting that exception you can use this workaround (until you get a valid certificate):
Just copy past this line to some where at the beginning of your flow. It will override the default certificate validation callback and always accept the certificate. If you want to stay safe, do not let this slip into production code.
ServicePointManager.ServerCertificateValidationCallback = (s, certificate, chain, sslPolicyErrors) => { return true; };

Comments