Error 400 when sending request to ESocial (C#)

I am receiving error 400 as response when executing SOAP request on esocial servers. The error occurs in this command:

using (HttpWebResponse resposta = request.GetResponse() as HttpWebResponse)
  • I installed the certificate chains.
  • I installed the strings by putting all certificates in the root repository of the local Machine
  • I installed the strings putting only the Brazilian Root Certificate Authority V5 in the root repository and the others in the intermediary repository.
  • install a Certificate (valid, not expired and with correct password) of my client in the personal repository (on the local Machine and on the current user).

It is worth saying that I can access the addresses of the webservices through the browser and the padlock turns green.

This Is My Code:

/// <summary>
/// Cria um webrequest SOAP para [Url]
/// </summary>
/// <returns></returns>
[HttpPost]
private static string enviarRequisicao()
{
    try
    {
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
        string web_service_teste =    "https://webservices.producaorestrita.esocial.gov.br/servicos/empregador/enviarloteeventos/WsEnviarLoteEventos.svc";                
        string xml_soap = @"C:\esocial\Templates\Esocial-S1000.xml";
        string url = web_service_teste;
        string response = "";
        Stream post = null;
        X509Certificate2 cert = new X509Certificate2(@"C:\esocial\certificado.pfx", "****");
        // build request objects to pass the data/xml to the server
        byte[] buffer = Encoding.ASCII.GetBytes(xml_soap);

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        
        request.Method = "POST";
        request.ContentType = "text/xml;charset=utf-8";                
        //request.Accept = "text/xml";
        request.ContentLength = buffer.Length;
        request.ClientCertificates.Add(cert);

        using (post = request.GetRequestStream())
        {
            // post data and close connection
            post.Write(buffer, 0, buffer.Length);
            post.Close();
        }

        using (HttpWebResponse resposta = request.GetResponse() as HttpWebResponse)
        {
            using (var stream = resposta.GetResponseStream())
            {
                using (var reader = new StreamReader(stream))
                {
                    var result = reader.ReadToEnd();
                    // Do something with result
                    return result;
                }
            }
        }
    }
    catch (WebException ex)
    {                
        throw ex;                
    }
}

This is the XML:

<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <soap:Body>
        <eSocial xmlns="http://www.esocial.gov.br/schema/lote/eventos/envio/v02_04_02">
            <envioLoteEventos grupo="1">
            <ideEmpregador>
                <tpInsc>1</tpInsc>
                <nrInsc>78294442</nrInsc>
            </ideEmpregador>
            <ideTransmissor>
                <tpInsc>1</tpInsc>
                <nrInsc>00254265000116</nrInsc>
            </ideTransmissor>
            <eventos>
                <evento Id="ID1333733250000002017122110411700002">
                    <eSocial xmlns="http://www.esocial.gov.br/schema/evt/evtTabRubrica/v02_04_02">
                        <evtInfoEmpregador Id="ID1027327500001832016021911320900001">
                        <ideEvento>
                            <tpAmb>2</tpAmb>
                            <procEmi>1</procEmi>
                            <verProc>1.0</verProc>
                        </ideEvento>
                        <ideEmpregador>
                            <tpInsc>1</tpInsc>
                            <nrInsc>78294442</nrInsc>
                        </ideEmpregador>
                        <infoEmpregador>
                            <inclusao>
                                <idePeriodo>
                                    <iniValid>2017-10</iniValid>
                                </idePeriodo>
                                <infoCadastro>
                                    <nmRazao>LIGA ARTE MOVEIS LTDA EPP</nmRazao>
                                    <classTrib>99</classTrib>
                                    <natJurid>399-</natJurid>
                                    <indCoop>0</indCoop>
                                    <indConstr>0</indConstr>
                                    <indDesFolha>0</indDesFolha>
                                    <indOptRegEletron>1</indOptRegEletron>
                                    <indEntEd>N</indEntEd>
                                    <indEtt>N</indEtt>
                                    <contato>
                                    <nmCtt>Cristiano dos Santos Lagame</nmCtt>
                                    <cpfCtt>09673071713</cpfCtt>
                                    <foneFixo>2122740494</foneFixo>
                                    </contato>
                                    <softwareHouse>
                                    <cnpjSoftHouse>00254265000116</cnpjSoftHouse>
                                    <nmRazao>LIGA ARTE MOVEIS LTDA EPP</nmRazao>
                                    <nmCont>Cristiano dos Santos Lagame</nmCont>
                                    <telefone>21993623199</telefone>
                                    <email>[email protected]</email>
                                    </softwareHouse>
                                    <infoComplementares>
                                    <situacaoPJ>
                                        <indSitPJ>0</indSitPJ>
                                    </situacaoPJ>
                                    <situacaoPF>
                                        <indSitPF>0</indSitPF>
                                    </situacaoPF>
                                    </infoComplementares>
                                </infoCadastro>
                            </inclusao>
                        </infoEmpregador>
                        </evtInfoEmpregador>
                        <Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
                        <SignedInfo>
                            <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
                            <SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" />
                            <Reference URI="">
                                <Transforms>
                                    <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
                                    <Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
                                </Transforms>
                                <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256" />
                                <DigestValue>...</DigestValue>
                            </Reference>
                        </SignedInfo>
                        <SignatureValue>...</SignatureValue>
                        <KeyInfo>
                            <X509Data>
                                <X509Certificate>TqIsONfPFt6L9tVM3CElBZeynQ1AlzzyZhpNX9YUTgiALPhv4eCxF/I0djghAj56FYBJMeWA4uwyGLA9L6VWMO1ksnuAsBHTWNd4/CI2IflwhlbCujgP91rBZOZJnr0YCQM9El92dUhVB0zBkFLvP14lDbyRIivF76ZlG3EeCCp8eCPi2QFoVY8N9tUpBNDSJPqkXSxgxvxPXQqfRsmwqoeVvd8sFKEmO4a5crmPbyExYOrrjoQoFhhgiagmS3O8rtjXBsWV9pKx435/mOMmU3/hGrWlIJfx4FQ7loqQZh/NVHRTXguMqua2m3QzSkVfw5oreZxbGUh9i0uZ0Dpocg==</X509Certificate>
                            </X509Data>
                        </KeyInfo>
                        </Signature>
                    </eSocial>
                </evento>
            </eventos>
            </envioLoteEventos>
        </eSocial>
    </soap:Body>
</soap:Envelope>

Detail, I got to have error 403, but solved through of this post .


Update: the XML was incorrect, found out here what was the correct formatting. I found it important to mention here that I changed the code to this below with the instructions of @ Pedro Gaspar:

private static string enviarRequisicao()
{
    try
    {
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
        //string web_service_teste = "https://webservices.producaorestrita.esocial.gov.br/servicos/empregador/enviarloteeventos/WsEnviarLoteEventos.svc";
        //              string web_service_producao = "https://webservices.envio.esocial.gov.br/servicos/empregador/enviarloteeventos/WsEnviarLoteEventos.svc";

        string urlXML = @"C:\esocial\Templates\Esocial-S1000.xml";

        X509Certificate2 x509Cert = new X509Certificate2(@"C:\esocial\certificado.pfx", "12345678");

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

        XDocument loteEventosXDoc = XDocument.Load(urlXML);

        var urlServicoEnvio = @"https://webservices.producaorestrita.esocial.gov.br/servicos/empregador/enviarloteeventos/WsEnviarLoteEventos.svc";
        var address = new EndpointAddress(urlServicoEnvio);
        var binding = new BasicHttpsBinding();  //Disponível desde .NET Framework 4.5
                                                // ou:
                                                //var binding = new BasicHttpBinding(BasicHttpsSecurityMode.Transport);
        binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;

        binding.MaxReceivedMessageSize = 768000;

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

        var wsClient = new PortalMadeirol.Web.ServiceEsocial.ServicoEnviarLoteEventosClient(binding, address);
        
        // Variável 'x509Cert' é do tipo X509Certificate2.

        wsClient.ClientCredentials.ClientCertificate.Certificate = x509Cert;

        var retornoEnvioXElement = wsClient.EnviarLoteEventos(loteEventosXDoc.Root);
        wsClient.Close();
    }
    catch (WebException ex)
    {
        throw ex;
    }
}
Author: Cristiano Lagame, 2018-09-10

1 answers

Cristiano, although I suggested in the comments that you create a reference to the eSocial service, through the WSDL of the service, and use the generated class that inherits System.ServiceModel.ClientBase, so that .NET does all the soap communication work for you, instead of you having to do everything in your hand (suggestion including that you accepted and already made it work), out of curiosity, and to try to answer your original question, I tried to make your original code work by accessing the eSocial "in your hand" through HttpWebRequest.

I had to make some corrections in XML, as you had already commented, in some namespaces, but I also had to include the group EnviarLoteEventos at the beginning of the message body, so the XML looked like this (I also exchanged your personal data):

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <soap:Body>
      <EnviarLoteEventos xmlnm="http://www.esocial.gov.br/schema/lote/eventos/envio/v1_1_1">
         <eSocial xmlns="http://www.esocial.gov.br/schema/lote/eventos/envio/v1_1_1">
            <envioLoteEventos grupo="1">
               <ideEmpregador>
                  <tpInsc>1</tpInsc>
                  <nrInsc>87654321</nrInsc>
               </ideEmpregador>
               <ideTransmissor>
                  <tpInsc>1</tpInsc>
                  <nrInsc>12345678901234</nrInsc>
               </ideTransmissor>
               <eventos>
                  <evento Id="ID1876543210000002017122110411700002">
                     <eSocial xmlns="http://www.esocial.gov.br/schema/evt/evtInfoEmpregador/v02_04_02">
                        <evtInfoEmpregador Id="ID1876543210001832016021911320900001">
                           <ideEvento>
                              <tpAmb>2</tpAmb>
                              <procEmi>1</procEmi>
                              <verProc>1.0</verProc>
                           </ideEvento>
                           <ideEmpregador>
                              <tpInsc>1</tpInsc>
                              <nrInsc>78294442</nrInsc>
                           </ideEmpregador>
                           <infoEmpregador>
                              <inclusao>
                                 <idePeriodo>
                                    <iniValid>2017-01</iniValid>
                                 </idePeriodo>
                                 <infoCadastro>
                                    <nmRazao>RAZÃO EMPREGADOR</nmRazao>
                                    <classTrib>99</classTrib>
                                    <natJurid>2062</natJurid>
                                    <indCoop>0</indCoop>
                                    <indConstr>0</indConstr>
                                    <indDesFolha>0</indDesFolha>
                                    <indOptRegEletron>1</indOptRegEletron>
                                    <indEntEd>N</indEntEd>
                                    <indEtt>N</indEtt>
                                    <contato>
                                       <nmCtt>Nome Contato</nmCtt>
                                       <cpfCtt>12345678901</cpfCtt>
                                       <foneFixo>2112345678</foneFixo>
                                    </contato>
                                    <softwareHouse>
                                       <cnpjSoftHouse>12345678901234</cnpjSoftHouse>
                                       <nmRazao>RAZÃO SOFTWAREHOUSE</nmRazao>
                                       <nmCont>Nome Contato</nmCont>
                                       <telefone>21123456789</telefone>
                                       <email>[email protected]</email>
                                    </softwareHouse>
                                    <infoComplementares>
                                       <situacaoPJ>
                                          <indSitPJ>0</indSitPJ>
                                       </situacaoPJ>
                                    </infoComplementares>
                                 </infoCadastro>
                              </inclusao>
                           </infoEmpregador>
                        </evtInfoEmpregador>
                        <Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
                           <SignedInfo>
                              <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
                              <SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" />
                              <Reference URI="">
                                 <Transforms>
                                    <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
                                    <Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
                                 </Transforms>
                                 <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256" />
                                 <DigestValue>...</DigestValue>
                              </Reference>
                           </SignedInfo>
                           <SignatureValue>...</SignatureValue>
                           <KeyInfo>
                              <X509Data>
                                 <X509Certificate>...</X509Certificate>
                              </X509Data>
                           </KeyInfo>
                        </Signature>
                     </eSocial>
                  </evento>
               </eventos>
            </envioLoteEventos>
         </eSocial>
      </EnviarLoteEventos>
   </soap:Body>
</soap:Envelope>

In the code I changed the way to read XML:

//byte[] buffer = Encoding.ASCII.GetBytes(xml_soap);
XDocument soapEnvelopeXml = XDocument.Load(xml_soap);

//[...]

   //post.Write(buffer, 0, buffer.Length);
   soapEnvelopeXml.Save(post);

And then the error went from 400 ("The remote server returned an error: (400) Bad Request.') for 500 ("The remote server returned an error: (500) Internal Server Error.").

Thanks to this answer here, do soEN: https://stackoverflow.com/a/21881566/8133067 , I improved the error handling to know exactly what error was going on, that's where I fixed the XML.

It was also essential to inform the SOAPAction in the Request Header, because this is what indicates which method of the service should be called.

So your changed code was like this:

private static string enviarRequisicao()
{
   try
   {
      string web_service_teste = "https://webservices.producaorestrita.esocial.gov.br/servicos/empregador/enviarloteeventos/WsEnviarLoteEventos.svc";
      string xml_soap = @"C:\esocial\Templates\Esocial-S1000.xml";
      string url = web_service_teste;
      X509Certificate2 cert = new X509Certificate2(@"C:\esocial\certificado.pfx", "****");

      //byte[] buffer = Encoding.ASCII.GetBytes(xml_soap);
      XDocument soapEnvelopeXml = XDocument.Load(xml_soap);

      ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
      HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

      request.Method = "POST";
      request.Headers.Add("SOAPAction", "http://www.esocial.gov.br/servicos/empregador/lote/eventos/envio/v1_1_0/ServicoEnviarLoteEventos/EnviarLoteEventos");
      request.ContentType = "text/xml;charset=utf-8";
      //request.Accept = "text/xml";
      //request.ContentLength = buffer.Length;
      request.ClientCertificates.Add(cert);

      using (Stream post = request.GetRequestStream())
      {
         // post data and close connection
         //post.Write(buffer, 0, buffer.Length);
         soapEnvelopeXml.Save(post);
         //post.Close();
      }

      using (HttpWebResponse resposta = request.GetResponse() as HttpWebResponse)
      {
         using (var stream = resposta.GetResponseStream())
         {
            using (var reader = new StreamReader(stream))
            {
               var result = reader.ReadToEnd();
               return result;
            }
         }
      }
   }
   catch (WebException webex)
   {
      WebResponse errResp = webex.Response;
      using (Stream respStream = errResp.GetResponseStream())
      {
         StreamReader reader = new StreamReader(respStream);
         string text = reader.ReadToEnd();
         return text;
      }
   }
}

The SOAPAction I discovered by looking at the WSDL of the service, at:

Https://webservices.producaorestrita.esocial.gov.br/servicos/empregador/enviarloteeventos/WsEnviarLoteEventos.svc?singleWsdl

This way worked for me.

 3
Author: Pedro Gaspar, 2018-09-13 16:45:52