Sanjoy Das2 Ответов: 1

Сообщение об ошибке : запрос был прерван: не удалось создать безопасный канал SSL/TLS.


Я использую следующий код в C#, чтобы прочитать веб-сайт SSL, на который приходит ошибка Error.txt -
Exception Read: The request was aborted: Could not create SSL/TLS secure channel.
:
//On the top of the page
using System.Net;
using System.IO;

//My methods
        private void btnGetData_Click(object sender, EventArgs e)
        {

            StringBuilder sb = new StringBuilder();

            try
            {

                // used on each read operation
                byte[] buf = new byte[8192];

                ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
                Uri uri = new Uri("https://www.zillow.com/homedetails/2138325511_zpid");
                WebRequest webRequest = WebRequest.Create(uri);
                WebResponse webResponse = webRequest.GetResponse();
                //ReadFrom(webResponse.GetResponseStream());
                Stream response = webResponse.GetResponseStream();


                string tempString = null;
                int count = 0;
                do
                {
                    // fill the buffer with data
                    count = response.Read(buf, 0, buf.Length);

                    // make sure we read some data
                    if (count != 0)
                    {
                        // translate from bytes to ASCII text
                        tempString = Encoding.ASCII.GetString(buf, 0, count);

                        // continue building the string
                        sb.Append(tempString);
                    }
                }
                while (count > 0); // any more data to read?
            }
            catch (Exception ex2)
            {
                try
                {

                    StreamWriter sw = new StreamWriter(Environment.CurrentDirectory + "\\Error.txt");

                    //Write a line of text
                    sw.WriteLine("Exception Read: " + ex2.Message);

                    //Close the file
                    sw.Close();
                    this.Close();
                    return;
                }
                catch(Exception exinner2)
                {
                    Console.WriteLine("Exception Read: " + exinner2.Message);
                    this.Close();
                    return;
                }
            }

            // write to text file page source
            try
            {

                //Pass the filepath and filename to the StreamWriter Constructor
                StreamWriter sw = new StreamWriter(Environment.CurrentDirectory + "\\Pageoutput.txt");

                //Write a line of text
                sw.WriteLine(sb.ToString());

                //Close the file
                sw.Close();
                MessageBox.Show("Data inserted Successfully");
            }
            catch (Exception ex)
            {
                try
                {

                    StreamWriter sw = new StreamWriter(Environment.CurrentDirectory + "\\Error.txt");

                    //Write a line of text
                    sw.WriteLine("Exception Write: " + ex.Message);

                    //Close the file
                    sw.Close();
                }
                catch (Exception exinner)
                {
                    Console.WriteLine("Exception Write: " + exinner.Message);
                }
            }

        }

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


Что я уже пробовал:

Я пробовал методом проб и ошибок из многих статей в интернете, но безрезультатно.

1 Ответов

Рейтинг:
5

#realJSOP

Там может быть любое количество причин, по которым это происходит.

0) убедитесь, что ваши сертификаты cert5ificates действительны.

1) Убедитесь, что IIS настроен правильно.

3) Измените свой код, если первые две вещи, которые я упомянул, в порядке. Это может помочь, но если ваши сертификаты недействительны или IIS неправильно настроен, это просто скроет реальную проблему.

ServicePointManager.Expect100Continue = true;
ServicePointManager.DefaultConnectionLimit = 9999;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;


Google/Bing - ваш друг.

Запрос был прерван: не удалось создать безопасный канал SSL/TLS. - Бинг[^]


Richard Deeming

#3 был бы моей ставкой - сервер поддерживает только TLS 1.2, который по умолчанию не включен в приложениях .NET до версии 4.7.

Для .NET 4.5 можно включите его через реестр[^]; но включение его в коде-более безопасный вариант.

Рекомендации по обеспечению безопасности транспортного уровня (TLS) с помощью платформы .NET Framework[^]

ali sbeiti

Спасибо, дорогая! Я изменил .net framework проекта на 4.6 и добавил приведенный выше код, и он работал.