如何使用https将WebRequest用于访问SSL加密站点?

Alf*_*son 106 c# webrequest

我正在编写一个程序,用于从用户提供的URL中读取内容.我的问题在于代码是这样的:

Uri uri = new Uri(url);
WebRequest webRequest = WebRequest.Create(uri);
WebResponse webResponse = webRequest.GetResponse();
ReadFrom(webResponse.GetResponseStream());
Run Code Online (Sandbox Code Playgroud)

如果提供的URL是"https://"URL,则会中断.任何人都可以帮助我更改此代码,以便它可以使用SSL加密的内容.谢谢.

小智 169

您正在以正确的方式执行此操作,但用户可能会向安装了无效SSL证书的站点提供URL.如果在发出实际Web请求之前放入此行,则可以忽略这些证书问题:

ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
Run Code Online (Sandbox Code Playgroud)

在哪里AcceptAllCertifications定义为

public bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
    return true;
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你的回答!为了避免一些无用的代码,我使用它像这样:ServicePointManager.ServerCertificateValidationCallback =(s,cert,chain,ssl)=> true; (41认同)
  • 我更喜欢`+ =委托{return true; }` (23认同)
  • 谢谢,你帮了我先生.F#使这更容易:``ServicePointManager.ServerCertificateValidationCallback < - Security.RemoteCertificateValidationCallback(fun _ _ _ _ - > true)`` (4认同)
  • @查尔斯·厄勒(Charles Ouellet)我想我甚至比你更懒惰,(a,b,c,d)=&gt;是 (2认同)
  • 请注意与此方法相关的潜在风险。有关更多信息,请参阅 /sf/answers/462940411/。 (2认同)

Gur*_*epS 18

您将对以下链接感兴趣:http://msdn.microsoft.com/en-us/library/ds8bxk2a.aspx

对于http连接,WebRequest和WebResponse类使用SSL与支持SSL的Web主机进行通信.决定使用SSL是由WebRequest类根据给定的URI做出的.如果URI以"https:"开头,则使用SSL; 如果URI以"http:"开头,则使用未加密的连接.

  • 您的回答暗示问题中的代码应该有效吗? (2认同)

Nan*_*ani 14

这个对我有用:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
Run Code Online (Sandbox Code Playgroud)