Error 400 when sending request to Esocial (C#)

Asked

Viewed 868 times

3

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

using (HttpWebResponse resposta = request.GetResponse() as HttpWebResponse)
  • I installed the certificate chains.
  • I installed the strings by placing all the certificates in the Root repository of Local Machine
  • I installed the chains placing only the Brazilian Root Certification Authority v5 in the Root repository and the others in the intermediate repository.
  • I installed the Certificate (valid, not expired and with correct password) of my client in the Personal repository (On Machine Location and Current User).

It is worth saying that I can access the addresses of the webservices by the browser and the lock is 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 the error 403, but I solved through of this post.


Updating: The XML was incorrect, discovered here which was the correct formatting. I thought it important to mention here that I changed the code to this below with the @Pedro Gaspar instructions:

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;
    }
}
  • Error 400 is usually related to the content you are sending, where the server is unable to validate as a valid request.

  • Tried sending without the post wrapper? just the <eSocial>?

  • Hello @Leandroangelo, I tried yes. I also believe this is the problem, so I would have to find some example of XML that works, right?

  • @Cristianolagame, but, why are you trying to make the SOAP "in hand" quiver, using HttpWeRequest instead of letting . NET do the job for you? Why don’t you create a reference to the service in Visual Studio and use the created class, which inherits the System.ServiceModel.ClientBase? In this same question you linked there is a link to an example code I wrote: https://answall.com/a/277465/86952, and there are several examples in several other questions here in the OS, but they are all similar.

  • Anyway, according to some examples I saw, you missed to inform the SOAP Action in the request header, as webRequest.Headers.Add("SOAPAction", action). But the examples I saw were accessing those old ASP.NET Web Service (ASMX) services, I don’t know if the same code would work for more modern services, remembering that access to the eSocial service uses the TLS security protocol.

  • @Cristianolagame, see this link: https://www.c-sharpcorner.com/forums/ssl-httpwebrequest-in-c-sharp-could-not-create-ssltls-secure-channel, remembering that the security protocol eSocial uses is TLS, it accepts versions 1.0, 1.1 and 1.2, although on some computers you may have problems using something other than TLS 1.0, see my question here: https://answall.com/q/318351/86952

  • Pedro, where does the x509Cert variable you mention in the other post come from? And I’m also not knowing how loteEventosXDoc.Root is filled, gives error here for me "Error CS0103: The name 'loteEventosXDoc' does not exist in the Current context".

  • Cristiano, the certificate you can load the same way you are doing, the result is already an object of type X509Certificate2, which is expected, and the variable loteEventosXDoc you can do so: XDocument loteEventosXDoc = XDocument.Load(xml_soap); (to use the type Xdocument you need to reference the library System.Xml.Linq).

  • But then, of course, I forgot to comment, you needed to change your test XML file, it could no longer contain the SOAP envelope, only the eSocial lot itself, because there the . NET would create the SOAP envelope and takes care of all this for you.

  • Calm down, I removed it, and I thank you for your attention so far. Now an error is being made before compiling, in line var wsClient = new Wsenviar.Servicoenviarloteeventosclient(Binding, address); The error is this: The type or namespace name 'Wsenviar' could not be found...

  • My code is like this because I called the service WsEnviar when I added the service reference to the project, but if you used a different name, you have to use the same name you used when adding it.

  • It worked! Returned the XML and there was the so dreamed message: Batch Received Successfully.

  • Just left to hit the XML, I received a warning "Incorrect Batch - Invalid Schema", but already fixed through the link below I found the correct XML formatting. https://answall.com/questions/281314/o-document-environment-n%C3%A3o-%C3%A9-um-xml-valido-do-esocial

  • Good Cristiano. If you can give a positive vote then there in the answers that helped you! This way you improve the visibility of the answers, because you are indicating that they were useful, and it also helps the author of the answer to earn some points and improve the reputation in Stack Overfow PT. ;-)

  • Only appears the option to flag as improper, not appearing in any of the answers the option to accept as answer... Inclusive I’ve read this link to see where the check mark should appear and I haven’t found: https://answall.com/help/one-answers

  • You can only mark as the answer when you asked the question, but you can click the up arrow to vote on the answer as useful (on the upper left side of each answer, and also of the questions). Have you already toured the site? https://answall.com/tour

  • I’ve already done the tour, and I was the one who asked the question... Strange, there are no arrows...

  • So Cristiano, you did this question, but this question did not get an answer! I was referring to the answers to the other questions, the links you posted, which helped you solve the problem: https://answall.com/a/307466/86952, https://answall.com/a/285167/86952 and https://pt.stackoverflowcom/a/277465/86952.

  • I don’t have 15 reputation points yet... so I can’t vote.

Show 14 more comments

1 answer

3


Cristiano, although he suggested in the comments that you create a reference to the service of eSocial, through the service WSDL, and use the generated class that inherits System.ServiceModel.ClientBase, so that the . NET does all the work of SOAP communication for you, instead of you having to do everything by 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, accessing eSocial "in hand" through the HttpWebRequest.

I had to make some corrections in XML, as you had already commented, in some namespaces, but also had to include the group EnviarLoteEventos at the beginning of the message body, so 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 I read the 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 mistake 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 that response here, from the O.R.EN: https://stackoverflow.com/a/21881566/8133067, I improved the error handling to know exactly what error was happening, that’s when I tidied up the XML.

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

Then your altered code went 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

That way it worked for me.

  • Pedro, have I told you today that you are the guy?! Perfect!

  • Thanks Cristiano, hehe... If you can, then give a positive vote there on the other answers that have helped you, now that you have enough reputation, to help give more visibility to the answers!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.