网络客户端 + HTTPS 问题
我目前正在与第三方创建的系统集成。 该系统要求我使用 XML/HTTPS 发送请求。 第 3 方向我发送了证书,我安装了它,
我使用以下代码:
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;
}
I am currently integrating with a system created by a 3rd party. This system requires me to send a request using XML/HTTPS. The 3rd party send me the certificate and I installed it
I use the following code:
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));
}
This code returns the following WebException
:
The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
UPDATE Because it's a test server I am working against, the certificate isn't trusted and validation fails... To bypass this in test/debug environment, create a new ServerCertificateValidationCallback
ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(bypassAllCertificateStuff);
and here is my "fake" callback
private static bool bypassAllCertificateStuff(object sender, X509Certificate cert, X509Chain chain, System.Net.Security.SslPolicyErrors error)
{
return true;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
允许所有证书的代码的最短表示法实际上是:
并且对于此错误效果很好。 不用说,您应该提供一个实际检查证书并根据证书信息决定通信是否安全的实现。 出于测试目的,请使用上面的代码行。
The shortest notation of the code to allow all certificates is actually:
And works well for this error. Needless to say that you should provide an implementation which actually checks the certificate and decides based on the certificate information if the communication is safe. For test purposes, use the above line of code.
对于原始答案的 VB.NET 版本,这里是(当需要使用“AddressOf”运算符连接事件时,转换器不能很好地工作)。 使用 WebClient() 或 HttpWebRequest() 对象之前的第一个代码:
..以及连接的方法代码:
For the VB.NET version of the original answer, here you go (converters don't work well when needing to wire up events with the 'AddressOf' operator). 1st code that goes before using a WebClient() or HttpWebRequest() object:
..and the wired up method code:
试试这个,它有效:
Try this, it works: