C# WebClient + HTTPS 问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/536352/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 07:12:33  来源:igfitidea点击:

WebClient + HTTPS Issues

c#httpswebclient

提问by rudigrobler

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

我目前正在与第三方创建的系统集成。该系统要求我使用 XML/HTTPS 发送请求。第 3 方将证书发送给我,然后我安装了它

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:

此代码返回以下内容WebException

The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.

底层连接已关闭:无法为 SSL/TLS 安全通道建立信任关系。

UPDATEBecause 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

更新因为它是我正在使用的测试服务器,证书不受信任并且验证失败......要在测试/调试环境中绕过它,请创建一个新的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;
}

Read more hereand here

在这里这里阅读更多

回答by atconway

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:

对于原始答案的 VB.NET 版本,您可以使用(当需要使用“AddressOf”运算符连接事件时,转换器无法正常工作)。使用 WebClient() 或 HttpWebRequest() 对象之前的第一个代码:

ServicePointManager.ServerCertificateValidationCallback = New System.Net.Security.RemoteCertificateValidationCallback(AddressOf bypassAllCertificateStuff)

..and the wired up method code:

..和有线方法代码:

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

回答by Koen Zomers

The shortest notation of the code to allow all certificates is actually:

允许所有证书的最短代码表示法实际上是:

ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

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.

并且适用于这个错误。不用说,您应该提供一个实际检查证书并根据证书信息决定通信是否安全的实现。出于测试目的,请使用上面的代码行。

回答by César Torres

Try this, it works:

试试这个,它有效:

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); }
}