System.Net.CertificatePolicy 到 ServerCertificateValidationCallback 接受所有证书策略 [英] System.Net.CertificatePolicy to ServerCertificateValidationCallback Accept all certificate policies

查看:23
本文介绍了System.Net.CertificatePolicy 到 ServerCertificateValidationCallback 接受所有证书策略的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我下载了一些有点过时的示例代码.它有以下类:

I've downloaded some sample code that is a bit outdated. It has the following class:

public class TrustAllCertificatePolicy : System.Net.ICertificatePolicy
{
    public TrustAllCertificatePolicy()
    { }

    public bool CheckValidationResult(ServicePoint sp,
              System.Security.Cryptography.X509Certificates.X509Certificate cert,
              WebRequest req, 
              int problem)
    {
        return true;
    }
}

稍后在代码中它会调用以下内容:

later on in the code it calls the following:

System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();

它给出以下警告:

警告 1 'System.Net.ServicePointManager.CertificatePolicy' 已过时:'CertificatePolicy 对于此类型已过时,请改用 ServerCertificateValidationCallback.http://go.microsoft.com/fwlink/?linkid=14202'

Warning 1 'System.Net.ServicePointManager.CertificatePolicy' is obsolete: 'CertificatePolicy is obsoleted for this type, please use ServerCertificateValidationCallback instead. http://go.microsoft.com/fwlink/?linkid=14202'

目前实现等效功能的程序是什么?

What is the current procedure to achieve the equivalent functionality?

我已阅读 MSDN 上的文章 但我不确定如何转换?这是一个类库.如果我似乎没有对此进行足够的研究,我深表歉意,但是当涉及到 ssl 证书时,它有点超出我的范围.非常感谢任何帮助!

I've read an article on MSDN but I'm unsure of how to convert? This is for a class library. I appologize if it seems as though I havn't researched this enough but when it comes to ssl certificates, it's a bit out of my realm. Any help is greatly appreciated!

推荐答案

在代码中包含以下类

 public static class SSLValidator
        {
            private static bool OnValidateCertificate(object sender, X509Certificate certificate, X509Chain chain,
                                                      SslPolicyErrors sslPolicyErrors)
            {
                return true;
            }
            public static void OverrideValidation()
            {
                ServicePointManager.ServerCertificateValidationCallback =
                    OnValidateCertificate;
                ServicePointManager.Expect100Continue = true;
            }
        }

然后在进行服务调用之前调用以下代码,但当您拥有真实证书时,请小心在生产环境中删除此代码

Then call the following before you make service call but be careful to remove this code on the production when you have real certs

SSLValidator.OverrideValidation();  

或者您可以执行以下操作以仅将其用于调试

Or you can do the following to use it only for debugging

#if DEBUG

            SSLValidator.OverrideValidation();
#endif 

这篇关于System.Net.CertificatePolicy 到 ServerCertificateValidationCallback 接受所有证书策略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆