Andre Silveira

Andre Silveira

  • 1.5k
  • 155
  • 14.4k

C# calling a soap webservice with authentication

Jun 24 2024 9:45 PM

Hi,

Im trying to make a call to a Webservice using SOP. The endpoint requires authentication with a certificate (pfx file).

I added the certificate to the code but it returns a error saying that 'anonymous client is not allowed'. Can anyone help me, please?

        var cert = new X509Certificate2("myCert.pfx", "myPassword");
        var binding = new BasicHtt psBinding();
        binding.Security.Mode = BasicHtt psSecurityMode.Transport;
        binding.Security.Transport.ClientCredentialType = Htt pClientCredentialType.Certificate;
        // Specify the endpoint address
        var endpoint = new EndpointAddress("the end point"); // I cannot post the link. The website wouldnt let me.
        var client = new NFeDistribuicaoDFeSoapClient(NFeDistribuicaoDFeSoapClient.EndpointConfiguration.NFeDistribuicaoDFeSoap, endpoint);
        client.ClientCredentials.ClientCertificate.Certificate = cert;
        var nfeDadosMsgXml = @"<distDFeInt xmlns=""no links allowed"">
                                  <tpAmb>2</tpAmb>
                                  <cUFAutor>35</cUFAutor>
                                  <CNPJ>000000000000000</CNPJ>
                                  <distNSU>
                                      <ultNSU>0</ultNSU>
                                  </distNSU>
                              </distDFeInt>";
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(nfeDadosMsgXml);
        var requestBody = new nfeDistDFeInteresseRequestBody { nfeDadosMsg = doc.DocumentElement };
        var request = new nfeDistDFeInteresseRequest(requestBody);

        try
        {
            var response = await client.nfeDistDFeInteresseAsync(doc.DocumentElement);
            Console.WriteLine(response.Body.nfeDistDFeInteresseResult.OuterXml);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error calling service: {ex.Message}");
       }

 

 


Answers (3)