Add customizable SOAP Header

Asked

Viewed 212 times

2

I’m consuming a web service SOAP which does not provide any information on Headers, nor of autenticação.

I added the same in my project by the tool Add Connected Service in Visual Studio.

Looking around the site, I found this topic: Add SOAP Header to SOAP C#

Who helped me create a Header and successfully add to my client:

var endpoint = new EndpointAddressBuilder(client.Endpoint.Address);                
                endpoint.Headers.Add(AddressHeader.CreateAddressHeader("cnpj", string.Empty, "xxxxxxxx"));
                endpoint.Headers.Add(AddressHeader.CreateAddressHeader("chave", string.Empty, "xxxxxxxx"));

client.Endpoint.Address = endpoint.ToEndpointAddress();

However, the Header expected by web service is different from the common:

 <soapenv:Header>
     <Autenticar>
         <cnpj>xxxxxxx</cnpj>
         <chave>xxxxxxx</chave>
     </Autenticar>
 </soapenv:Header>

Has an object <Autenticar> within the Header.

I’ve tried that topic too Adding SOAP implicit headers to WSDL, however, without success.

How can I add that <Autenticar> inside my Header?

1 answer

3


Create a class that identifies the object you want to send in the header.

Example:

[DataContract(Namespace = "")]
public class autenticar
{
    [DataMember]
    public string cnpj { get; set; }

    [DataMember]
    public string chave { get; set; }
}

Then encapsulate your client in a scope and add your objects to the message header:

using (var scope = new OperationContextScope(client.InnerChannel))
{
    var autenticar = new autenticar() { chave = "minha chave", cnpj = "meu cnpj" };
    var autenticarHeader = MessageHeader.CreateHeader("autenticar", string.Empty, autenticar);
    OperationContext.Current.OutgoingMessageHeaders.Add(autenticarHeader);

    //Aqui você consume o webservice
}

The result will be this:

inserir a descrição da imagem aqui

  • No words, thank you very much!!!

  • 1

    You’re welcome @Perozzo.

Browser other questions tagged

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