CommunicationException: Error in client when making HTTP request (HTTP.SYS) to third party WebService

Posted on

Question :

I’ve been developing for eSocial for over a year already, and I’m encountering the following error on some clients when trying to send the service:


System.ServiceModel.CommunicationException :
Error while doing HTTP request for link . This may be related to the fact that the server certificate is not correctly configured with HTTP.SYS in the HTTPS case. This could also be caused by a security association mismatch between the client and the server.


—> System.Net.WebException : The underlying connection was closed: Unexpected error in a submission.
  — > System.IO.IOException : Unable to read data from the transport connection: An existing connection was forced to be terminated by the remote host.
  — > System.Net.Sockets.SocketException : The termination of an existing connection by the remote host in System.Net.Sockets.Socket.Receive (Byte [] buffer, Int32 offset, Int32 size , SocketFlags socketFlags) …

On most computers the program is working perfectly, only on some computers this problem happens. My target platform is the .NET Framework 4.7.

I’ve already answered two questions about this error here in the OS:


(1) Problems communicating with the webservice provided by the government
  (2) Error communicating https with WebService

And from the research I’ve done, there are two solutions to the problem:

  • Set the ServicePointManager.SecurityProtocol property ( link );
  • Install Windows Update updates ( link ).
  • For the first solution: The eSocial service uses the TLS 1.2 security protocol , but this is not always the default machine configuration. I already did this in the code and not solved in most cases:

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

    In the case of the second solution: In the searches I did the problem could happen on computers with Windows 7 outdated, and theoretically the update via Windows Update would solve, but in most cases did not solve, and I have even caught some cases of this error in Windows 10.

    I even ran a test program, with the message log and trace trace linked, to see if I could get any more information, but the only other thing I found out (because of tracing ) is that the error occurs when the message is sent by the channel (communication with WebService ).

    Here is the code I’m using to instantiate and call the service:

     const string UrlSvcBase = @"https://webservices.{0}{1}";
     string urlServico = String.Format(UrlSvcBase, "producaorestrita", @"enviarloteeventos/WsEnviarLoteEventos.svc");
     var address = new EndpointAddress(urlServico);
     //var binding = new BasicHttpBinding(BasicHttpsSecurityMode.Transport);
     var binding = new BasicHttpsBinding();  //Disponível desde .NET Framework 4.5
     binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
     // Manual de Orientação do Desenvolvedor v1.4, página 39, item '5.4.5. Validações aplicadas':
     // "O tamanho limite da mensagem SOAP é 750 kbytes."
     // O valor padrão da propriedade MaxReceivedMessageSize é 65.536,
     // que é alterado então para 750 KB * 1024 = 768.000 bytes.
     // Caso contrário, ocorre a exceção:
     //   Exception: System.ServiceModel.CommunicationException
     //   InnerException: System.Exception {System.ServiceModel.QuotaExceededException}
     //   "The maximum message size quota for incoming messages (65536) has been exceeded.
     //    To increase the quota, use the MaxReceivedMessageSize property on the appropriate binding element."  
     //   HResult: -2146233087 (0x80131501)
     binding.MaxReceivedMessageSize = 768000;
     ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls |
                                            SecurityProtocolType.Tls11 |
     var wsClient = new WsEnviar.ServicoEnviarLoteEventosClient(binding, address);
     // Variável 'certificado' é do tipo X509Certificate2.
     wsClient.ClientCredentials.ClientCertificate.Certificate = certificado;
     // Variavel 'lote' é do tipo XElement.
     var retorno = wsClient.EnviarLoteEventos(lote);

    Does anyone have any idea what might cause this error, or any idea of what else I can do to try to figure out the cause of the problem?


    Answer :

    According to the @EProgrammerNotFound comment, it seems to be a .NET bug. With me it was the same thing when I transmitted the E-Finance to Webservice SPED on some Windows 7 and Windows 2008 machines.

    I ended up creating a routine that would use a Stack with the protocols I want to use (TLS 1.0, TLS 1.1 and TLS 1.2). Then I uncork and assign one protocol at a time and I’m trying to send it. If it fails, I move on to the next protocol:

    ServicePointManager.SecurityProtocol = (SecurityProtocolType) 0;    
    // Pilha com protocolos que vou utilizar
    Stack<SecurityProtocolType> protocolosDisponiveis = new Stack<SecurityProtocolType>();
    protocolosDisponiveis.Push((SecurityProtocolType)768); // TLS 1.1
    protocolosDisponiveis.Push((SecurityProtocolType)3072); // TLS 1.2.
    var TentarNovamente = false;
        ServicePointManager.SecurityProtocol = this.protocolosDisponiveis.Pop();
            // Tenta chamar o serviço se der certo ok eu saio fora
            TentarNovamente = false;
        catch (CommunicationException ex)
            TentarNovamente = true;
    while(TentarNovamente && protocolosDisponiveis.Count() > 0);


    Leave a Reply

    Your email address will not be published. Required fields are marked *