使用C#设置CertificatePolicy=$TrustAll

本文关键字:TrustAll CertificatePolicy 设置 使用 | 更新日期: 2023-09-27 18:20:53

我目前在powershell中使用此代码:

$TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")
    [System.Net.ServicePointManager]::CertificatePolicy=$TrustAll

我如何在C#中做到这一点?

使用C#设置CertificatePolicy=$TrustAll

这里有一个信任每个证书的示例。

using System;
using System.IO;
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class Program : ICertificatePolicy {
    public bool CheckValidationResult (ServicePoint sp, 
        X509Certificate certificate, WebRequest request, int error)
    {
        return true;
    }
    public static void Main (string[] args) 
    {
        ServicePointManager.CertificatePolicy = new Program ();
        WebRequest wr = WebRequest.Create (args [0]);
        Stream stream = wr.GetResponse ().GetResponseStream ();
        Console.WriteLine (new StreamReader (stream).ReadToEnd ());
    }
}

如果你想了解更多关于这个主题的信息(例如,备选方案),我建议你阅读Mono关于这个话题的维基文章。

也许这会有所帮助:

[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}