Kembo
Kembo

Reputation: 87

Authentication with Soap service in C# console

I am trying to connect to a soap service(wsdl) from the console in C#. My code is fairly simple, I added the wsdl to the project as a service reference, and the proxy class(?) was created as expected.

The service use a authentication key per message, and i cannot find anywhere to add it to the soap header. As a reference, this is the code i run inside my main method:

Api.Servicereference1.PortClient object = new Api.Servicereference1.PortClient();                        
object.testmethod();

The output from this piece is the following:

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        <testmethod xmlns="http://wsdlserver.com/soap"/>
    </s:Body>
</s:Envelope>

However, what i want to achive is the following message sent, with the authentication:

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <s:Header>
        <s:auth>key</s:auth>
    </s:Header>
    <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">        
        <testmethod xmlns="http://wsdlserver.com/soap"/>
    </s:Body>
</s:Envelope>

Can anyone help me in the right direction, as to how I can add this custom header to my messages? Thanks.

Upvotes: 0

Views: 1976

Answers (2)

Kembo
Kembo

Reputation: 87

Ok, thanks for the input,I did some reading, and figured that if I surround my message with an OperationContextScope I am able to add headers as I please. I changed my code to:

Api.Servicereference1.PortClient object = new Api.Servicereference1.PortClient();
using ( OperationContextScope scope = new OperationContextScope(object.InnerChannel))
{
     MessageHeader soapheader = MessageHEader.CreateHeader("name","ns",payload);
     OperationContext.Current.OutgoingMessageHeaders.Add(soapheader);
     object.testmethod();
}

The parameters in MessageHeader.CreateHeader() is explained here MessageHeader.CreateHeader Method (String, String, Object) from msdn.microsoft.com

Although this solution would require me to manually add an OperationContext to all my messages, it solves the issue of custom soapheaders for me.

Upvotes: 0

jlew
jlew

Reputation: 10601

Article on how to add custom headers to WCF client proxies:

Adding custom headers to every WCF call - a solution

Upvotes: 1

Related Questions