WebClient + HTTPS问题

我目前正在与第三方创build的系统进行整合。 这个系统要求我使用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

底层连接已closures:无法build立SSL / TLS安全通道的信任关系。

更新由于这是一个testing服务器,我正在处理,证书不受信任,validation失败…要绕过此testing/debugging环境中创build一个新的ServerCertificateValidationCallback

 ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(bypassAllCertificateStuff); 

这是我的“假”callback

 private static bool bypassAllCertificateStuff(object sender, X509Certificate cert, X509Chain chain, System.Net.Security.SslPolicyErrors error) { return true; } 

在这里和这里阅读更多

代码允许所有证书的最短符号实际上是:

 ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; 

并为这个错误很好地工作。 不用说,你应该提供一个实际检查证书的实现,并根据证书信息来决定通信是否安全。 出于testing目的,使用上面的代码行。

对于原始答案的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 

试试这个,它的工作原理:

 class Ejemplo { static void Main(string[] args) { string _response = null; string _auth = "Basic"; Uri _uri = new Uri(@"http://api.olr.com/Service.svc"); string addres = @"http://api.olr.com/Service.svc"; string proxy = @"http://xx.xx.xx.xx:xxxx"; string user = @"platinum"; string pass = @"01CFE4BF-11BA"; NetworkCredential net = new NetworkCredential(user, pass); CredentialCache _cc = new CredentialCache(); WebCustom page = new WebCustom(addres, proxy); page.connectProxy(); _cc.Add(_uri, _auth, net); page.myWebClient.Credentials = _cc; Console.WriteLine(page.copyWeb()); } } public class WebCustom { private string proxy; private string url; public WebClient myWebClient; public WebProxy proxyObj; public string webPageData; public WebCustom(string _url, string _proxy) { url = _url; proxy = _proxy; myWebClient = new WebClient(); } public void connectProxy() { proxyObj = new WebProxy(proxy, true); proxyObj.Credentials = CredentialCache.DefaultCredentials; myWebClient.Proxy = proxyObj; } public string copyWeb() { return webPageData = myWebClient.DownloadString(url); } }