How to ignore a certificate error with c# 2.0 WebClient - without the certificate

后端 未结 6 2061
时光说笑
时光说笑 2020-11-28 06:42

Using Visual Studio 2005 - C# 2.0, System.Net.WebClient.UploadData(Uri address, byte[] data) Windows Server 2003

So here\'s a stripped down version of

6条回答
  •  有刺的猬
    2020-11-28 07:11

    I realize this is an old post, but I just wanted to show that there is a more short-hand way of doing this (with .NET 3.5+ and later).

    Maybe it's just my OCD, but I wanted to minimize this code as much as possible. This seems to be the shortest way to do it, but I've also listed some longer equivalents below:

    // 79 Characters (72 without spaces)
    ServicePointManager.ServerCertificateValidationCallback = (a, b, c, d) => true;
    

    Shortest way in .NET 2.0 (which is what the question was specifically asking about)

    // 84 Characters
    ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
    

    It's unfortunate that the lambda way requires you to define the parameters, otherwise it could be even shorter.

    And in case you need a much longer way, here are some additional alternatives:

    ServicePointManager.ServerCertificateValidationCallback = (sender, cert, chain, errors) => true;
    
    ServicePointManager.ServerCertificateValidationCallback = delegate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; };
    
    // 255 characters - lots of code!
    ServicePointManager.ServerCertificateValidationCallback =
        new RemoteCertificateValidationCallback(
            delegate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
            {
                return true;
            });
    

提交回复
热议问题