System.Net.HttpWebRequest不包含ServercertificateValidationCallback的定义

时间:2017-12-16 06:15:18

标签: c# .net-4.5 clr

我正在尝试编译后面的课程:

public partial class CLRTest
{
     [Microsoft.SqlServer.Server.SqlProcedure]
     public static void TestApi()
     {
          Uri  uri = new Uri("https://wrong.host.badssl.com/");
          HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;
          request.ServerCertificateValidationCallback += Validator;
          ...
     }

     public static bool Validator (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)

     {
          return true;
     }     
}

并收到错误System.Net.HttpWebRequest does not contain a definition for ServerCertificateValidationCallback。如何解决?

P.S。在控制台应用程序中,我没有这样的错误。

1 个答案:

答案 0 :(得分:2)

解决ServicePointManager,因为HttpWebRequest从中继承了属性ServerCertificateValidationCallback

public partial class CLRTest
{
    [Microsoft.SqlServer.Server.SqlFunction]
    public static SqlString TestApi(SqlString url)
    {
        IgnoreBadCertificates();
        Uri uri = new Uri(url.ToString());
        HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;
        try
        {
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            using (Stream receive = response.GetResponseStream())
            using (StreamReader stream = new StreamReader(receive, Encoding.UTF8))
            {
                return stream.ReadToEnd();
            }
        }
        catch (Exception ex)
        {
            return ex.ToString();
        }
    }

    public static void IgnoreBadCertificates()
    {
        ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(AcceptAllCertifications);
    }

    private static bool AcceptAllCertifications(object sender, X509Certificate certification, X509Chain chain, SslPolicyErrors sslPolicyErrors)
    {
        return true;
    }
}