Joe
Joe

Reputation: 255

Adding a custom namespace to soap envelop in WCF

I am calling a service, which needs a particular namespace added to the soap envelop.

for example here is my sample regular soap message

    <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"  xmlns:sec="ANOTHER NAMESPACE THAT I WANT TO ADD" >
      <s:Header>

     </s:Header>
    <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <xyz xmlns="">
   <customerId>2511</customerId>
  </xyz>
   </s:Body>
   </s:Envelope>

I am already implementing IDispatchMessageInspector, IClientMessageInspector for some other purpose, i m not sure if i have to do something there to add the extra namespace.

Upvotes: 2

Views: 10738

Answers (2)

Rick Strahl
Rick Strahl

Reputation: 17671

You can add the namespaces as part of a custom Message implementation, which includes a OnWriteStartEnvelope() method you can override and add any custom namespaces to. You then hook up the Message to a MessageFormatter and then use a MessageFormatAttribute to attach the behavior to specific methods.

The key method that adds the namespaces are on the overridden Message implementation where you can add namespaces to the Envelope:

protected override void OnWriteStartEnvelope(XmlDictionaryWriter writer)
{
        writer.WriteStartElement("soapenv", "Envelope", "http://schemas.xmlsoap.org/soap/envelope/");
        writer.WriteAttributeString("xmlns", "oas", null, "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
        writer.WriteAttributeString("xmlns", "v2", null, "http://www.royalmailgroup.com/api/ship/V2");
        writer.WriteAttributeString("xmlns", "v1", null, "http://www.royalmailgroup.com/integration/core/V1");
        writer.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance");
        writer.WriteAttributeString("xmlns", "xsd", null, "http://www.w3.org/2001/XMLSchema");            
}

Once attached to the Envelope the rest of the document will then reuse these top level declared namespaces and not inline the namepsaces.

I wrote up a blog post that describes the full process which involves Message, MessageFormatter and FormatMessageAttribute implementations: http://weblog.west-wind.com/posts/2016/Apr/02/Custom-Message-Formatting-in-WCF-to-add-all-Namespaces-to-the-SOAP-Envelope

Upvotes: 1

atatko
atatko

Reputation: 481

If you've generated your code through svcutil or by adding an external reference, you can do the following:

[System.ServiceModel.ServiceContractAttribute(Namespace = "ANOTHER NAMESPACE THAT I WANT TO ADD", Name = "sec")]
public partial class TheClassYouAreUsingForAClient {  }

This should allow you to add the namespace without modifying your generated code.

Upvotes: 0

Related Questions