User Tools

Site Tools

blog:2023-06-27_c_system.net.webexception_要求已經中止_無法建立_ssl_tls_的安全通道



2023-06-27 C#: System.Net.WebException: '要求已經中止: 無法建立 SSL/TLS 的安全通道。'

  • When I am trying to create a connection by C#. Some web will throw “System.Net.WebException: '要求已經中止: 無法建立 SSL/TLS 的安全通道。'” error exception.

Solution

  • Add this code piece before create link
    System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
    System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls;
    
  • So, my code become as follows:
            private void TASK_DownloadStart()
            {
                // 開始下載
                System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls;
                WebRequest request = WebRequest.Create(textBox_url.Text);
                WebResponse response = request.GetResponse();
    
                Stream data = response.GetResponseStream();
                string html = String.Empty;
                using (StreamReader sr = new StreamReader(data))
                {
                    html = sr.ReadToEnd();
                }
                richTextBox_Log.AppendText(html);
                richTextBox_Log.ScrollToCaret();
            }
  • Note that this solution need .NET 4.5+

TAGS

  • 50 person(s) visited this page until now.

Permalink blog/2023-06-27_c_system.net.webexception_要求已經中止_無法建立_ssl_tls_的安全通道.txt · Last modified: 2023/06/27 15:36 by jethro

oeffentlich