Ошибка the underlying connection was closed an unexpected error occurred on a receive

Обновлятор-1с. Ошибка при скачивании исправлений (патчей)

Ошибка ‘Не найдено ни одного сервера с размещенным сервисом’    оглавление    Ошибка ‘Запрос был прерван: Не удалось создать защищенный канал SSL/TLS’.

2022-08-23T15:04:56+00:00

Проблема

Начиная с 13.08.2022 перестали скачиваться исправления (патчи) к конфигурациям с ошибкой:

«The underlying connection was closed: An unexpected error occurred on a send»

или то же самое на русском

«Базовое соединение закрыто: Непредвиденная ошибка при передаче.»

Временное решение

Как временное решение, можно использовать:

  • установку исправлений (патчей) из самой 1С
  • из обновлятора из локальной папки: ссылка

Причина и ход решения

15.08.2022 Предварительно, я полагаю, что у сервиса 1С изменились технические требования к версии протокола шифрования, который используется для соединения (исправления, в отличие от обновлений скачиваются через API соответствующего сервиса 1С). Сегодня (в понедельник) я приступил к решению проблемы — на днях будет новый билд, я напишу о его выходе в соц. сетях (vk, tg) и на этой страничке.

16.08.2022 Да, дело в изменившейся минимальной версии TLS, которую требует сервис 1С для скачивания исправлений. Сегодня, максимум завтра выйдет новая версия обновлятора, где часть кода, ответственная за скачивание исправлений будет вынесена в отдельный исполняемый файл, который для своего выполнения потребует также установленный на компьютере .Net Framework 4.5 (в большинстве современных ОС он уже входит в систему).  Это ещё один довод в пользу запланированного на начало следующего года полного перехода на эту версию фреймворка (сейчас большая часть функционала обновлятора требует только .Net Framework 3.5).

16.08.2022 Вышла версия обновлятора от 16 августа с решением возникшей проблемы. Нажмите кнопку «Скачать новый обновлятор» внизу главного окна уже установленного обновлятора. Восстановлена возможность скачивания исправлений (патчей). Обратите внимание, что для скачивания исправлений (патчей) теперь необходим также установленный .Net Framework 4.5 или выше (он уже предустановлен в большинстве современных ОС). После обновления обновлятора на эту версию сразу проверьте возможность скачивания новых исправлений — если необходимой версии .Net Framework у вас на компьютере нет — обновлятор скажет об этом и даст соответствующую ссылку для установки. На начало 2023 года запланирован полный переход обновлятора на .Net Framework 4.5: ссылка.

23.08.2022 На старых ОС для корректной работы TLS должны быть установлены некоторые обновления, иначе возникает ошибка ‘Не удалось создать защищенный канал SSL/TLS’ или ‘Could not create SSL/TLS secure channel’: подробнее здесь.

С уважением, Владимир Милькин (преподаватель школы 1С программистов и разработчик обновлятора).

Владимир Милькин

Как помочь сайту: расскажите (кнопки поделиться ниже) о нём своим друзьям и коллегам. Сделайте это один раз и вы внесете существенный вклад в развитие сайта. На сайте нет рекламы, но чем больше людей им пользуются, тем больше сил у меня для его поддержки.

Нажмите одну из кнопок, чтобы поделиться:

Ошибка ‘Не найдено ни одного сервера с размещенным сервисом’    оглавление    Ошибка ‘Запрос был прерван: Не удалось создать защищенный канал SSL/TLS’.

I have the following code:

private Uri currentUri;

private void Form1_Load(object sender, EventArgs e)
{
    currentUri = new Uri(@"http://www.stackoverflow.com");
    HttpWebRequest myRequest = (HttpWebRequest) HttpWebRequest.Create("http://www.stackoverflow.com");
    WebProxy myProxy = new WebProxy("120.198.230.8:81");
    myRequest.Proxy = myProxy;

    HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();

    webBrowser1.DocumentStream = myResponse.GetResponseStream();

    webBrowser1.Navigating += new WebBrowserNavigatingEventHandler(webBrowser1_Navigating);
}

void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
    if (e.Url.AbsolutePath != "blank")
    {
        currentUri = new Uri(currentUri, e.Url.AbsolutePath);
        HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(currentUri);

        HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();

        webBrowser1.DocumentStream = myResponse.GetResponseStream();
        e.Cancel = true;
    }
}

after compiling:

error: An unhandled exception of type ‘System.Net.WebException’
occurred in System.dll

Additional information: The underlying connection was closed: An
unexpected error occurred on a receive.

at line HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();

Please help me.

Uwe Keim's user avatar

Uwe Keim

39k56 gold badges175 silver badges289 bronze badges

asked Feb 12, 2014 at 13:03

Thomas's user avatar

0

Setting the HttpWebRequest.KeepAlive to false didn’t work for me.

Since I was accessing a HTTPS page I had to set the Service Point Security Protocol to Tls12.

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

Notice that there are other SecurityProtocolTypes: SecurityProtocolType.Ssl3, SecurityProtocolType.Tls, SecurityProtocolType.Tls11

So if the Tls12 doesn’t work for you, try the three remaining options.

Also notice that you can set multiple protocols. This is preferable on most cases.

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

Edit: Since this is a choice of security standards it’s obviously best to go with the latest (TLS 1.2 as of writing this), and not just doing what works. In fact, SSL3 has been officially prohibited from use since 2015 and TLS 1.0 and TLS 1.1 will likely be prohibited soon as well. source: @aske-b

Community's user avatar

answered May 8, 2017 at 9:57

Bartho Bernsmann's user avatar

Bartho BernsmannBartho Bernsmann

2,3731 gold badge25 silver badges33 bronze badges

5

The underlying connection was closed: An unexpected error occurred on a receive.

This problem occurs when the server or another network device
unexpectedly closes an existing Transmission Control Protocol (TCP)
connection. This problem may occur when a time-out value on the
server or on the network device is set too low. To resolve this
problem, see resolutions A, D, E, F, and O. The problem can also
occur if the server resets the connection unexpectedly, such as if an
unhandled exception crashes the server process. Analyze the server
logs to see if this may be the issue.

Resolution

To resolve this problem, make sure that you are using the most recent version of the .NET Framework.

Add a method to the class to override the GetWebRequest method. This change lets you access the HttpWebRequest object. If you are using Microsoft Visual C#, the new method must be similar to the following.

class MyTestService:TestService.TestService
{
    protected override WebRequest GetWebRequest(Uri uri)
    {
        HttpWebRequest webRequest = (HttpWebRequest) base.GetWebRequest(uri);
        //Setting KeepAlive to false
        webRequest.KeepAlive = false;
        return webRequest;
    }
}

Excerpt from KB915599: You receive one or more error messages when you try to make an HTTP request in an application that is built on the .NET Framework 1.1 Service Pack 1.

Andrew T.'s user avatar

Andrew T.

4,6718 gold badges43 silver badges62 bronze badges

answered Feb 12, 2014 at 13:09

Nagaraj S's user avatar

Nagaraj SNagaraj S

13.2k6 gold badges32 silver badges52 bronze badges

3

  • .NET 4.6 and above. You don’t need to do any additional work to support TLS 1.2, it’s supported by default.
  • .NET 4.5. TLS 1.2 is supported, but it’s not a default protocol. You need to opt-in to use it. The following code will make TLS 1.2 default, make sure to execute it before making a connection to secured resource:
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12

  • .NET 4.0. TLS 1.2 is not supported, but if you have .NET 4.5 (or above) installed on the system then you still can opt in for TLS 1.2 even if your application framework doesn’t support it. The only problem is that SecurityProtocolType in .NET 4.0 doesn’t have an entry for TLS1.2, so we’d have to use a numerical representation of this enum value:
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12

  • .NET 3.5 or below. TLS 1.2 is not supported. Upgrade your application to more recent version of the framework.

answered Aug 20, 2019 at 10:35

Daniyal Saleem's user avatar

2

None of the solutions out there worked for me. What I eventually discovered was the following combination:

  • Client system: Windows XP Pro SP3
  • Client system has .NET Framework 2 SP1, 3, 3.5 installed
  • Software targeting .NET 2 using classic web services (.asmx)
  • Server: IIS6
  • Web site «Secure Communications» set to:
    • Require Secure Channel
    • Accept client certificates

enter image description here

Apparently, it was this last option that was causing the issue. I discovered this by trying to open the web service URL directly in Internet Explorer. It just hung indefinitely trying to load the page. Disabling «Accept client certificates» allowed the page to load normally. I am not sure if it was a problem with this specific system (maybe a glitched client certificate?) Since I wasn’t using client certificates this option worked for me.

answered Feb 15, 2016 at 17:29

Hugh Jeffner's user avatar

Hugh JeffnerHugh Jeffner

2,9364 gold badges31 silver badges31 bronze badges

My Hosting server block requesting URL And code site getting the same error
Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host

enter image description here

After a lot of time spent and apply the following step to resolve this issue

  1. Added line before the call web URL

    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

  2. still issue not resolve then I upgrade .net version to 4.7.2 but I think it’s optional

  3. Last change I have checked my hosting server security level which causes to TLS handshaking for this used «https://www.ssllabs.com/ssltest/index.html» site
    and also check to request URL security level then I find the difference is requested URL have to enable a weak level Cipher Suites you can see in the below image

enter image description here

Now here are my hosting server supporting Cipher Suites

enter image description here

here is called if you have control over requesting URL host server then you can sync this both server Cipher Suites. but in my case, it’s not possible so I have applied the following script in Windows PowerShell on my hosting server for enabling required weak level Cipher Suites.

Enable-TlsCipherSuite -Name "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384"
Enable-TlsCipherSuite -Name "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256"
Enable-TlsCipherSuite -Name "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA"
Enable-TlsCipherSuite -Name "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA"
Enable-TlsCipherSuite -Name "TLS_DHE_RSA_WITH_AES_256_CBC_SHA"
Enable-TlsCipherSuite -Name "TLS_DHE_RSA_WITH_AES_128_CBC_SHA"
Enable-TlsCipherSuite -Name "TLS_RSA_WITH_AES_256_GCM_SHA384"
Enable-TlsCipherSuite -Name "TLS_RSA_WITH_AES_128_GCM_SHA256"
Enable-TlsCipherSuite -Name "TLS_RSA_WITH_AES_256_CBC_SHA256"
Enable-TlsCipherSuite -Name "TLS_RSA_WITH_AES_128_CBC_SHA256"
Enable-TlsCipherSuite -Name "TLS_RSA_WITH_AES_256_CBC_SHA"
Enable-TlsCipherSuite -Name "TLS_RSA_WITH_AES_256_CBC_SHA"

after applying the above script my hosting server Cipher Suites level look like

enter image description here

Then my issue resolved.

Note: server security level downgrade is not a recommended option.

answered Oct 7, 2020 at 11:33

Amol Shiledar's user avatar

Before Execute query I put the statement as below and it resolved my error.
Just FYI in case it will help someone.

ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
ctx.ExecuteQuery();

answered Sep 4, 2019 at 15:30

Rahul Patil's user avatar

2

To expand on Bartho Bernsmann’s answer, I should like to add that one can have a universal, future-proof implementation at the expense of a little reflection:

static void AllowAllSecurityPrototols()
{   int                  i, n;
    Array                types;
    SecurityProtocolType combined;

    types = Enum.GetValues( typeof( SecurityProtocolType ) ); 
    combined = ( SecurityProtocolType )types.GetValue( 0 );

    n = types.Length;
    for( i = 1; i < n; i += 1 )
    {   combined |= ( SecurityProtocolType )types.GetValue( i );  }

    ServicePointManager.SecurityProtocol = combined;
}

I invoke this method in the static constructor of the class that accesses the internet.

answered Jul 17, 2020 at 14:46

Anton Shepelev's user avatar

I was working also on web scraping project and same issue found, below code applied and it worked nicely. If you are not aware about TLS versions then you can apply all below otherwise you can apply specific.

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;

answered Nov 8, 2019 at 10:27

Anjan Kant's user avatar

Anjan KantAnjan Kant

3,90039 silver badges38 bronze badges

3

User767034699 posted

Hi there guys,

lately been having a problem sending and receiving response from thirdparty webservice. I have developed a windows service which runs for every 10 mins sending and receiving response from them. Their soap service uses https enabled with ssl/tls protocols.
when the service is installed and running on my local machine. It runs with no problem at all. I have this bit of code before sending request to and also have enabled network tracing on the app

 System.Net.ServicePointManager.Expect100Continue = true;
                   System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; 

result from the log file that i have on my local machine is able to show that the validation is good. 

System.Net Information: 0 : [21820] SecureChannel#50478517 — Remote certificate was verified as valid by the user.
System.Net Information: 0 : [21820] ProcessAuthentication(Protocol=Tls12, Cipher=Aes128 128 bit strength, Hash=Sha1 160 bit strength, Key Exchange=44550 384 bit strength).
System.Net.Sockets Verbose: 0 : [21820] Entering Socket#4476320::Send()

System.Net Information: 0 : [21820] Connection#55178356 — Created connection from 192.168.208.226:24506 to 41.183.202.16:443.
System.Net Information: 0 : [21820] TlsStream#11882963::.ctor(host=»clients host address», #certs=0, checkCertificateRevocationList=False, sslProtocols=Tls11, Tls12)

But when i deploy the windows service to production server i get the below error 

ystem.Net.Sockets Error: 0 : [10596] Socket#10359806::UpdateStatusAfterSocketError() — ConnectionReset
System.Net.Sockets Error: 0 : [10596] Exception in Socket#10359806::Receive — An existing connection was forcibly closed by the remote host.
System.Net.Sockets Verbose: 0 : [10596] Exiting Socket#10359806::Receive() -> Int32#0
System.Net.Sockets Verbose: 0 : [10596] Socket#10359806::Dispose()
System.Net Error: 0 : [10596] Exception in HttpWebRequest#44831880:: — The underlying connection was closed: An unexpected error occurred on a send..
System.Net Error: 0 : [10596] Exception in HttpWebRequest#44831880::GetResponse — The underlying connection was closed: An unexpected error occurred on a send..

i have also downloaded the ceritficates from digicert but still no change at all. What could be the fix for this help will be appreciated.

kind regards

Tony

0 / 0 / 1

Регистрация: 19.07.2011

Сообщений: 48

1

Программа теряет соединение с сервером, в чем причина

10.01.2012, 11:42. Показов 5398. Ответов 5


Добрый день. В лог пишется такая ошибка «The underlying connection was closed: An unexpected error occurred on a receive.» Запуская на виртуальной машине. Программа конектитя к ftp и скачивает файлики с него. ОС: win server 2003 Enterprise Edition/ На другой машине рабочей, не виртуально работает программа.

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



56 / 56 / 10

Регистрация: 27.12.2011

Сообщений: 141

10.01.2012, 12:52

2

Прога теряет соединение во время скачивания файла с фтп? И почему не запустить прогу сразу под сервер без виртуальной машины… расскажите по подробней, на чём прога написана и есть ли исходники.



0



vladso

0 / 0 / 1

Регистрация: 19.07.2011

Сообщений: 48

10.01.2012, 13:23

 [ТС]

3

на рабочей машине всё ок. Просто мне нужно отладить на виртуалке. Написано на С#

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
private List<string> getFileList(string FTPAddress, string username, string password)
        {
            var files = new List<string>();
 
            try
            {
                var request = FtpWebRequest.Create(FTPAddress) as FtpWebRequest;
 
                request.Method = WebRequestMethods.Ftp.ListDirectory;
                request.Credentials = new NetworkCredential(username, password);
                request.UsePassive = true;
                request.UseBinary = true;
                request.KeepAlive = false;
 
               // FtpWebResponse response = request.GetResponse() as FtpWebResponse;
                FtpWebResponse response = (FtpWebResponse)request.GetResponse();        //здесь ошибка
 
                Stream responseStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(responseStream);
 
                while (!reader.EndOfStream)
                {
                    files.Add(reader.ReadLine());
                }
 
                reader.Close();
                responseStream.Close(); //redundant
                response.Close();
            }
            catch (Exception ex)
            {
                SaveToLog(ex.Message);
            }
            return files;
        }



0



56 / 56 / 10

Регистрация: 27.12.2011

Сообщений: 141

10.01.2012, 14:28

4

Прога вообще начинает скачивать файлы или соединение сразу закрывается?

Добавлено через 1 минуту
Просто на виртуальной машине зачастую бывают проблемы с сетевыми дровами

Добавлено через 5 минут
Прога ругается что соединение с сервером закрыто при первом обращении к серверу, т.е. не факт что соединение вообще удалось установить. Либо проблема с дровами, либо что-то блокирует соединение. А на той машине где прога работает какая система стоит?



0



0 / 0 / 1

Регистрация: 19.07.2011

Сообщений: 48

10.01.2012, 14:48

 [ТС]

5

Я понял в чем проблема, это домен блокирует соединение. Я решил не замарачиваться просто в ручную скопировать фалы и так забирать.



0



56 / 56 / 10

Регистрация: 27.12.2011

Сообщений: 141

10.01.2012, 14:51

6

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



1



Problem

User launches Controller client. User receives an error.

Symptom

image-20181121073932-1

The underlying connection was closed: An unexpected error occurred on a receive.
   at System.Web.Services.Protocols.WebClientProtocol.GetWebResponse(WebRequest request)
   at System.Web.Services.Protocols.HttpWebClientProtocol.GetWebResponse(WebRequest request)
   at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
   at Cognos.Controller.ControllerSoapHttpClientProtocol.Invoke(String methodname, Object[] parameters)
   at Cognos.Controller.Proxy.Light.WSLight.CheckServerConnection(String sGuid, String sUser)
   at Cognos.Controller.Direct.ServerInfoD.CheckServerConnection()
   at CCR.AppContext.CheckConnectionToServer()

Cause

The ‘The underlying connection was closed: An unexpected error occurred on a receive‘ error can occur at different times when using Controller client.

  • This Technote *only* relates to the scenario where the error occurs immediately after launching the client
  • If the error occurs when you are using Controller’s functionality (after you have successfully logged in) then see explanations inside separate IBM Technotes.

There are several known causes of this error when launching the client:

  •  Scenario #1 — The Controller application server’s Windows SSL/TLS/security protocols had been partially disabled (locked down), so that only a very few protocols were enabled
    • Typically (most likely) it is caused by customers disabling TLS 1.0 and 1.1 (leaving only TLS 1.2 available)
    • For more details, see separate IBM Technote #276599.
  •  Scenario #2 — Both of the following are true:
    • Controller client configured to use SSL (HTTPS) for its communication (to the Controller application server)
    • Client (and/or the application server) has been configured to disable some required SSL/TLS communication protocols.
      • For more details, see separate IBM Technote #2015415.
  • Scenario #3 — Client device (and/or Controller application server) has Microsoft patch KB4467697 installed.
  • Scenario #4 — (32-bit Excel link error only, not ‘main’ Controller client) — The client device does not contain the required 32-bit registry key to force the use of TLS 1.2 for .NET
    • For more details, see separate IBM Technote #0956557.

Resolving The Problem

Scenario #1

Fix: Reconfigure Controller client to use the relevant communication protocol (typically TLS 1.2)

Workaround: Re-enable the relevant/required IIS communication protocols (on the application server).

  • For more details, see separate IBM Technote #276599.

Scenario #2

Reconfigure the client device (plus also the application server if necessary) so that the required protocols are enabled.

  • For more details, see separate IBM Technote #2015415.

Scenario #3

Uninstall Microsoft patch KB4467697 from client device:

image-20181121091306-1

  • If the problem remains, uninstall the same patch from the Controller application server.

Scenario #4
Add the 32-bit registry key (in other words, inside «Wow6432Node«), to force 32-bit .NET applications to use TLS 1.2.

  • For more details, see separate IBM Technote #0956557.

Related Information

[{«Business Unit»:{«code»:»BU059″,»label»:»IBM Software w/o TPS»},»Product»:{«code»:»SS9S6B»,»label»:»IBM Cognos Controller»},»Component»:»»,»Platform»:[{«code»:»PF033″,»label»:»Windows»}],»Version»:»All Versions»,»Edition»:»»,»Line of Business»:{«code»:»LOB10″,»label»:»Data and AI»}}]

What should have been just another quick PowerShell script performing a WebRequest to get some data, turned into a debugging session when both the Invoke-RestMethod and Invoke-WebRequest PowerShell commands were returning; The underlying connection was closed: An unexpected error occurred on a send.

Invoke-RestMethod

Here is the PowerShell Invoke-RestMethod response that returns: The underlying connection was closed: An unexpected error occurred on a send.

Invoke-RestMethod : The underlying connection was closed: An unexpected error occurred on a send.
At line:1 char:15
+ ... postdata2 = Invoke-RestMethod -Uri $post.URL -Method Get -UserAgent $ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

Invoke-WebRequest

Here is the PowerShell Invoke-WebRequest response that returns: The underlying connection was closed: An unexpected error occurred on a send.

Invoke-WebRequest : The underlying connection was closed: An unexpected error occurred on a send.
At line:3 char:21
+ ... $postdata = Invoke-WebRequest -Uri $post.URL -Method Get -UserAgent $ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

Due to PowerShell defaults, it’s not unusual to have issues with TLS. The ambiguous nature of this error did however make me jump to the conclusion that I probably just needed to enforce TLS 1.2. This can be done using this PowerShell one-liner:

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

However, in this situation that wasn’t the fix. Thinking it was still TLS related I checked out the SSL Certificate for the URI I was making my webrequests against. Looking at the certificate showed it was valid.

Powershell - An unexpected error occurred on a send - Certificate is Valid.PNG

Solution

After a lot of searching I was able to work around the problem using scenarios from (here and here), however they weren’t ideal.

The resolution and solution I’m using to resolve the problem is to allow TLS, TLS 1.1 and TLS 1.2.

Insert the following line before invoking your PowerShell WebRequest using either Invoke-RestMethod or Invoke-WebRequest.

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls -bor [Net.SecurityProtocolType]::Tls11 -bor [Net.SecurityProtocolType]::Tls12

Summary

Hopefully this helps others experiencing this error, and allows me to quickly find it again next time I encounter this issue.

Also checkout my PowerShell Snippets Vol 1  and Vol 2 for other simple resolutions to ambiguous errors and tasks.

The underlying connection was closed: an unexpected error occurred on a send.

To resolve the PowerShell “underlying connection was closed” error, in your PowerShell script enable TLS:

Add the following line before your Invoke-RestMethod or Invoke-WebRequest call;

  1. [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls -bor
    [Net.SecurityProtocolType]::Tls11 -bor [Net.SecurityProtocolType]::Tls12

Applies To : PowerShell

Hello everyone

I am posting the same question again. Because i did not get any reply from my previous question.
I am working on an application. Its a window application which developed in .net 2.0

Now the problem is this that when ever i run my application and i send a request to another application its send successfully but i get the problem when i get the response its show me the error and the error is

The underlying connection was closed: An unexpected error occurred on a receive.

here is my code

public string tm4b(string sURL, bool bEscapeURL, string sPostData)
{
sURL = sURL.Trim();
while (sURL.IndexOf(" ") > 0)
{
sURL = sURL.Replace(" ", " ");
}
System.Text.StringBuilder sb = new System.Text.StringBuilder();
string stmp = string.Empty;
Uri httpUri = new Uri(sURL, bEscapeURL);
try
{
 
System.Text.ASCIIEncoding byteConverter = new System.Text.ASCIIEncoding();
byte[] byte1 = byteConverter.GetBytes(sPostData);
System.Net.HttpWebRequest hwRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(httpUri);
 
hwRequest.ContentType = "application/x-www-form-urlencoded";
hwRequest.Method = "POST";
 
hwRequest.ContentLength = sPostData.Length; ;
System.IO.Stream PostStream = hwRequest.GetRequestStream();
PostStream.Write(byte1, 0, byte1.Length);
System.Net.HttpWebResponse hwResponse = (System.Net.HttpWebResponse)hwRequest.GetResponse();
System.IO.StreamReader sRead = new System.IO.StreamReader(hwResponse.GetResponseStream(),
System.Text.Encoding.ASCII);
 
if ((stmp = sRead.ReadLine()) != null)
{
 
sb.Append(stmp + "");
 
}
 
PostStream.Close();
sRead.Close();
 
return sb.ToString();
 
}
catch (Exception ex)
{
 
return "error";
}
return "Request Error";
 
}

But its give me this error for only one url and for anothers url its working well

Please check the code and error and please tell me what i have to do
i tried all the logics that i can use but did not get any good results

So experts please help me

Updated 15-Jun-21 21:14pm


If your service is https then add this line before webclient call

ServicePointManager.SecurityProtocol = (SecurityProtocolType)768 | (SecurityProtocolType)3072;

«But its give me this error for only one url and for anothers url its working well» — that’s the important point. Which URL is it? Does the URL work when you use it from a common web browser (e.g. Internet Explorer)? When the server decides to close the connection, you’ll get an error in your client code, and that is actually correct behavior of your client. If the server is also yours, check what the server is doing with that URL.

This is related to TLS, Just upgrade the .net to the latest version.

This happens when the server denies tlsv1.0 or tlsv1.0 is disabled from the server side.
To resolve this from the client side just upgrade to the latest version and see.

I use fidler on machine in which the application is running and add this code in app config

<system.net>
<settings>
<httpwebrequest useunsafeheaderparsing="true" />
</settings>
</system.net>

Its working then but when i exit the fidler then its give me error what is the reason please tell me

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://api.guesty.com/api/v2/listings");
                webRequest.KeepAlive = false;
                webRequest.ProtocolVersion = HttpVersion.Version11;
                webRequest.Timeout = 60000;
                ServicePointManager.Expect100Continue = false;
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Ssl3;
                webRequest.Method = "GET";
                webRequest.ContentType = "application/json";
                webRequest.ContentLength = 0;
                string autorization = "******" + ":" + "******";
                byte[] binaryAuthorization = System.Text.Encoding.UTF8.GetBytes(autorization);
                autorization = Convert.ToBase64String(binaryAuthorization);
                autorization = "Basic " + autorization;
                webRequest.Headers.Add("Authorization", autorization);
                var response = webRequest.GetResponse();


  • Вопрос задан

    более трёх лет назад

  • 2348 просмотров

Пригласить эксперта

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Ssl3;

Попробуй убрать два последних значения. Может отфутболивать из-за использования ненадежных методов шифрования.


  • Показать ещё
    Загружается…

12 февр. 2023, в 02:07

2000 руб./за проект

12 февр. 2023, в 00:06

1000 руб./в час

11 февр. 2023, в 22:57

25000 руб./за проект

Минуточку внимания

Понравилась статья? Поделить с друзьями:
  • Ошибка u0001 82 range rover evoque
  • Ошибка u0100 форд фокус
  • Ошибка the ue4 summercamp game has crashed and will close
  • Ошибка u0100 тойота ярис
  • Ошибка the system has been destroyed xiaomi