我目前正在与第三方创建的系统集成.该系统要求我使用XML/HTTPS发送请求.第三方发给我证书,我安装了它
我使用以下代码:
using (WebClient client = new WebClient()) { client.Headers.Add(HttpRequestHeader.ContentType, "text/xml"); System.Text.ASCIIEncoding encoding=new System.Text.ASCIIEncoding(); var response = client.UploadData(address, "POST", encoding.GetBytes(msg)); }
此代码返回以下内容WebException
:
底层连接已关闭:无法为SSL/TLS安全通道建立信任关系.
更新因为它是我正在反对的测试服务器,证书不受信任且验证失败...要在测试/调试环境中绕过它,请创建一个新的ServerCertificateValidationCallback
ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(bypassAllCertificateStuff);
这是我的"假"回调
private static bool bypassAllCertificateStuff(object sender, X509Certificate cert, X509Chain chain, System.Net.Security.SslPolicyErrors error) { return true; }
在这里和这里阅读更多
允许所有证书的代码的最短表示法实际上是:
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
并且适用于此错误.不用说,您应该提供实际检查证书的实现,并根据证书信息决定通信是否安全.出于测试目的,请使用上面的代码行.
对于原始答案的VB.NET版本,这里你去(当需要使用'AddressOf'运算符连接事件时,转换器不能正常工作).使用WebClient()或HttpWebRequest()对象之前的第一个代码:
ServicePointManager.ServerCertificateValidationCallback = New System.Net.Security.RemoteCertificateValidationCallback(AddressOf bypassAllCertificateStuff)
..和有线方法代码:
Private Shared Function bypassAllCertificateStuff(ByVal sender As Object, ByVal cert As X509Certificate, ByVal chain As X509Chain, ByVal [error] As System.Net.Security.SslPolicyErrors) As Boolean Return True End Function