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.
– Leandro Angelo
Tried sending without the post wrapper? just the
<eSocial>
?– Leandro Angelo
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?
– Cristiano Lagame
@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 theSystem.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.– Pedro Gaspar
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.– Pedro Gaspar
@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 Gaspar
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 Lagame
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 variableloteEventosXDoc
you can do so:XDocument loteEventosXDoc = XDocument.Load(xml_soap);
(to use the type Xdocument you need to reference the librarySystem.Xml.Linq
).– Pedro Gaspar
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.
– Pedro Gaspar
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...
– Cristiano Lagame
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.– Pedro Gaspar
It worked! Returned the XML and there was the so dreamed message: Batch Received Successfully.
– Cristiano Lagame
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
– Cristiano Lagame
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. ;-)
– Pedro Gaspar
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
– Cristiano Lagame
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
– Pedro Gaspar
I’ve already done the tour, and I was the one who asked the question... Strange, there are no arrows...
– Cristiano Lagame
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.
– Pedro Gaspar
I don’t have 15 reputation points yet... so I can’t vote.
– Cristiano Lagame