我正在尝试编译课程:
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。在控制台应用程序中,我没有这样的错误。
用 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;
}
}