Adding SOAP Header to request

Anupdas picture Anupdas · May 23, 2014 · Viewed 12.1k times · Source

I have been trying to add a header to SOAP request as follows

<soapenv:Header>
     <UsernameToken xmlns="http://test.com/webservices">username</UsernameToken>
     <PasswordText xmlns="http://test.com/webservices">password</PasswordText>
     <SessionType xmlns="http://test.com/webservices">None</SessionType>
</soapenv:Header>

I have found suggestions to use SoapHeader to include header values, but introduces another level such as

<soapenv:Header>
    <CustomHeader>
        <UsernameToken xmlns="http://test.com/webservices">username</UsernameToken>
        <PasswordText xmlns="http://test.com/webservices">password</PasswordText>
        <SessionType xmlns="http://test.com/webservices">None</SessionType>
    </CustomHeader>
</soapenv:Header>

Can anyone suggest how I can form a request without CustomHeader.

Answer

GSerjo picture GSerjo · May 23, 2014

Try to use this one

private static void Main()
{
    using (var client = new ServiceClient())
    using (var scope = new OperationContextScope(client.InnerChannel))
    {
        MessageHeader usernameTokenHeader = MessageHeader.CreateHeader("UsernameToken",
            "http://test.com/webservices", "username");
        OperationContext.Current.OutgoingMessageHeaders.Add(usernameTokenHeader);

        MessageHeader passwordTextHeader = MessageHeader.CreateHeader("PasswordText",
            "http://test.com/webservices", "password");
        OperationContext.Current.OutgoingMessageHeaders.Add(passwordTextHeader);

        MessageHeader sessionTypeHeader = MessageHeader.CreateHeader("SessionType",
            "http://test.com/webservices", "None");
        OperationContext.Current.OutgoingMessageHeaders.Add(sessionTypeHeader);

        string result = client.GetData(1);
        Console.WriteLine(result);
    }
    Console.ReadKey();
}

The Service Trace viewer shows following

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <s:Header>
        <UsernameToken xmlns="http://test.com/webservices">username</UsernameToken>
        <PasswordText xmlns="http://test.com/webservices">password</PasswordText>
        <SessionType xmlns="http://test.com/webservices">None</SessionType>
        <To s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">http://localhost:13332/Service1.svc</To>
        <Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">http://tempuri.org/IService/GetData</Action>
    </s:Header>
</s:Envelope>

Take a look OperationContextScope for more info