Customize WCF Envelope and Namespace Prefix


WCF allows you to customize the response using DataContract, MessageContract or XmlSerializer. With DataContract you have access only to the body of the message while MessageContract will let you control the headers of the message too. However, you don't have any control over namespace prefixes or on the soap envelope tag from the response message.

When generating the response, WCF uses some default namespaces prefixes and we cannot control this from configuration. For example, <s:Envelope xmlns:s="">. Normally, the prefix should not be a problem according to SOAP standards. However, there are times when we need to support old clients who manually parse the response and they expect fixed format or look for specific prefixes.

Real world example

Recently, I was asked to rewrite an old service using .NET and WCF, keeping compatibility with existing clients. The response from WCF looked like this:

<s:envelope xmlns:s="">
<getcardinforesponse xmlns="" xmlns:i="">
<api_key />
<reference_id />

The expected response for existing clients was:

<soap-env:envelope xmlns:soap-env="" xmlns:ns1="">
<ns1:getcardinforesponse xmlns:i="">
<ns1:api_key />
<ns1:reference_id />

The two messages are equivalent from SOAP or XML perspective. What I needed to do in order to obtain the expected result was:

Possible solutions

There are multiple extension points where the message can be altered

Custom MessageEncoder

You can alter the xml output using a MessageEncoder. A good example about this can be found here.

This approach has several disadvantages, as the author also pointed out in the end of the article:

Custom MessageFormatter and a derived Message class

The MessageFormatter is used to transform the result of your method into an instance of Message class. This instance is then passed in the WCF pipeline (message inspectors, channels, encoders). This is the right place to transform your message because all the other extension points will work with the exact same message that you are sending to your clients

The following diagram shows how the message is sent accross different layers in WCF pipeline. You can see that the MessageFormatter is just before the MessageInspector when you send a message from server to client, while the MessageEncoder is a side component which is activated right before the transport layer.

WCF Extension Points

Additional information about the diagram can be found here

Creating a custom MessageFormatter

First, you need to create a IDispatchMessageFormatter class. This is the message formatter. The SerializeReply method will return an instance of your custom Message class.

public class MyCustomMessageFormatter : IDispatchMessageFormatter
private readonly IDispatchMessageFormatter formatter;

public MyCustomMessageFormatter(IDispatchMessageFormatter formatter)
this.formatter = formatter;

public void DeserializeRequest(Message message, object[] parameters)
this.formatter.DeserializeRequest(message, parameters);

public Message SerializeReply(MessageVersion messageVersion, object[] parameters, object result)
var message = this.formatter.SerializeReply(messageVersion, parameters, result);
return new MyCustomMessage(message);

Inherit from Message class

Custom message class

This is the class that will allow you to alter the output of your service.

public class MyCustomMessage : Message
private readonly Message message;

public MyCustomMessage(Message message)
this.message = message;
public override MessageHeaders Headers
get { return this.message.Headers; }
public override MessageProperties Properties
get { return this.message.Properties; }
public override MessageVersion Version
get { return this.message.Version; }
protected override void OnWriteStartBody(XmlDictionaryWriter writer)
writer.WriteStartElement("Body", "");
protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
protected override void OnWriteStartEnvelope(XmlDictionaryWriter writer)
writer.WriteStartElement("SOAP-ENV", "Envelope", "");
writer.WriteAttributeString("xmlns", "ns1", null, "");

Custom message class explained

The derived Message class has several overrides that you can use to obtain the required XML:

Activate the MessageFormatter

To activate the MessageFormatter we will create an OperationBehavior attribute that must be applied to the methods (on the interface) that we want to use this MessageFormatter.

public class MobilityProviderFormatMessageAttribute : Attribute, IOperationBehavior
public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters) { }

public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation) { }

public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
var serializerBehavior = operationDescription.Behaviors.Find<datacontractserializeroperationbehavior>();

if (dispatchOperation.Formatter == null)
((IOperationBehavior)serializerBehavior).ApplyDispatchBehavior(operationDescription, dispatchOperation);

IDispatchMessageFormatter innerDispatchFormatter = dispatchOperation.Formatter;

dispatchOperation.Formatter = new MyCustomMessageFormatter(innerDispatchFormatter);

public void Validate(OperationDescription operationDescription) { }