Wednesday, May 30, 2018

Customize WCF Envelope and Namespace Prefix



Introduction


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="http://schemas.xmlsoap.org/soap/envelope/">. 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="http://schemas.xmlsoap.org/soap/envelope/">
 <s:body>
 <getcardinforesponse xmlns="https://vanacosmin.ro/WebService/soap/" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
 <control_area>
 <source>OVF</source>
 <ns1:source_send_date>2014-01-06T14:15:37.1505943+01:00</ns1:source_send_date>
 <api_key />
 <message_id>27970411614463393270</message_id>
 <correlation_id>1</correlation_id>
 </control_area>
 <chip_uid>1111</chip_uid>
 <tls_engraved_id>************1111</tls_engraved_id>
 <reference_id />
 <is_blocked>false</is_blocked>
 <is_useable>false</is_useable>
 <registration_date>2013-12-13T13:06:39.75</registration_date>
 <last_modification>2013-12-20T15:48:52.307</last_modification>
 </getcardinforesponse>
 </s:body>
</s:envelope>
The expected response for existing clients was:

<soap-env:envelope xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="https://vanacosmin.ro/WebService/soap/">
 <soap-env:body>
 <ns1:getcardinforesponse xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
 <ns1:control_area>
 <ns1:source>OVF</ns1:source>
 <ns1:source_send_date>2014-01-06T14:15:37.1505943+01:00</ns1:source_send_date>
 <ns1:api_key />
 <ns1:message_id>27970411614463393270</ns1:message_id>
 <ns1:correlation_id>1</ns1:correlation_id>
 </ns1:control_area>
 <ns1:chip_uid>1111</ns1:chip_uid>
 <ns1:tls_engraved_id>************1111</ns1:tls_engraved_id>
 <ns1:reference_id />
 <ns1:is_blocked>false</ns1:is_blocked>
 <ns1:is_useable>false</ns1:is_useable>
 <ns1:registration_date>2013-12-13T13:06:39.75</ns1:registration_date>
 <ns1:last_modification>2013-12-20T15:48:52.307</ns1:last_modification>
 </ns1:getcardinforesponse>
 </soap-env:body>
</soap-env:envelope>
The two messages are equivalent from SOAP or XML perspective. What I needed to do in order to obtain the expected result was:


  • Change the namespace prefix for SOAP envelope
  • Add another namespace with the prefix ns1 in the SOAP envelope
  • Remove the namespace from s:body (because it was moved on a top level)

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:

The message encoder is activated late in the WCF pipeline. If you have message security, a hash is already included in the message. Changing the message will invalidate the hash.
You can build a custom channel so that the changing of the message takes place before the hash is calculated. This is complicated, and the next drawback applies.
If you are using a message inspector (e.g. for logging), you will log the message in its initial state, and not in the form sent to the customer.
If you make big changes to the message, your wsdl contract will not work, so you need to do additional work for metadata exchange, if you want your service to be consumed by new clients without manually parsing your message.

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", "http://schemas.xmlsoap.org/soap/envelope/");
 }
 protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
 {
 this.message.WriteBodyContents(writer);
 }
 protected override void OnWriteStartEnvelope(XmlDictionaryWriter writer)
 {
 writer.WriteStartElement("SOAP-ENV", "Envelope", "http://schemas.xmlsoap.org/soap/envelope/");
 writer.WriteAttributeString("xmlns", "ns1", null, "https://vanacosmin.ro/WebService/soap/");
 }
}

Custom message class explained

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


  • All the methods will use the same XmlDictionaryWriter. This means that if you add a namespace with a prefix, that prefix will be used for the next elements that you add in the same namespace.
  • OnWriteStartEnvelope Method is called first. By default this method will write the s prefix and will add namespaces according to the soap version. I use this method to change the prefix to "SOAP-ENV" and also to add the ns1 namespace.
  • OnWriteStartBody is called second. By default, this method will still use the prefix s for body. This is why I had to override it and write the Body element using the XmlDictionaryWriter.
  • OnWriteBodyContents is called last in this sequence. By calling WriteBodyContents on the original message, I will get the expected result because I have declared the namespace ns1 at the top level
  • There are other methods that you can override if you need more flexibility.


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.

[AttributeUsage(AttributeTargets.Method)]
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 MobilityProviderMessageFormatter(innerDispatchFormatter);
 }
 public void Validate(OperationDescription operationDescription) { }
}

Custom Message Formatting in WCF - Namespaces to the SOAP Envelope


I've been working on a WCF client implementation that is calling into a rather peculiar service that is unable to handle messages sent from a WCF SOAP client. In particular the service I needed to call does not allow inline namespaces in the SOAP message and requires that all namespaces are declared with prefixes and declared on the SOAP:Envelope element. WCF by default doesn't work that way.

It felt like I entered into the real bizarro world of a service that was refusing valid XML messages because the messages were formatted a certain way. Specifically the service refuses to read inline namespace declaration and expects all the namespaces to be declared up front on the SOAP envelope. Yeah, you heard that right – send valid XML with validating namespace definitions, but which happen to be defined inline of the body rather than at the top of the envelope and the service fails with a hard exception on the backend.

Hmmm alrighty then… After a lot of back and forth with the provider it comes out that, yes "that's a known issue" and it will be fixed – sometime in the future to which I mentally added "presumably in the next 10 years". Not bloody likely that they are going to help me on the server side.

So since I wasn't going to get any help from the provider, I did what any good developer would do – search StackOverflow and the Web for a solution. Apparently this is not the most bizarre thing ever, as I assumed. A lot of Java/IBM based service apparently have this problem, but even so WCF solutions for this seem to be scarce. I even posted my own StackOverflow question, which I eventually answered myself with what I'm describing here in more detail.

Defining the Problem


To demonstrate what I'm talking about,here's a simple request that WCF natively creates when calling the service:

To demonstrate what I'm talking about,here's a simple request that WCF natively creates when calling the service:

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Header>
    <h:Security>...</h:Security>
  </s:Header>
  <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <cancelShipmentRequest xmlns="http://www.royalmailgroup.com/api/ship/V2">
      <integrationHeader>
        <dateTime xmlns="http://www.royalmailgroup.com/integration/core/V1">2016-04-02T01:39:06.1735839Z</dateTime>
        <version xmlns="http://www.royalmailgroup.com/integration/core/V1">2</version>
        <identification xmlns="http://www.royalmailgroup.com/integration/core/V1">
          <applicationId>RMG-API-G-01</applicationId>
          <transactionId>vw7nj5jcmtkc</transactionId>
        </identification>
      </integrationHeader>
      <cancelShipments>
        <shipmentNumber>TTT001908905GB</shipmentNumber>
      </cancelShipments>
    </cancelShipmentRequest>
  </s:Body>
</s:Envelope>
This is pretty typical of WCF messages which include a bunch of inline and duplicated namespace declarations. Some of them inherit down (like on cancelShipmentRequest) and others are defined on the actual nodes and repeated (all of the v1 namespaces basically). I'm not quite sure why WCF creates such verbosity in its messages rather than defining namespaces at the top since it is a lot cleaner, but regardless, what's generated matches the schema requirements of the WSDL and in theory the XML sent should work just fine.

But - as pointed out, the provider does not accept inline namespace declarations in the body, so no matter what I tried the requests were getting kicked back with 500 errors from the server. As you might expect, it a look a lot of trial and error and head beating to figure out that the namespaces were the problem. After confirming with the provider this is indeed the problem, a known problem with no workaround, on the server side and it became clear that the only way to get the service to work is to fix it on the client in the WCF Proxy.

Customizing the XML Message using a MessageFormatter
After a lot of digging (and a comment on my StackOverflow question that referenced this blog post) the solution was to implement a custom MessageFormatter in WCF. MessageFormatters sit inside of the WCF pipeline and get fired after a document has been created but before the message has been processed. This gives a chance to hook into various creation events and modify the message as its being created. Essentially I need to hook into the Envelope element creation and then add the namespaces and when creating a subclassed message object there is a way to hook into the Envelope generation event and at that time it's possible to inject the namespaces. And it turns out that this approach works – the namespaces get generated at the Envelope level in the SOAP document.

Creating a custom Message Object with WCF

The key element that has to be modified to handle the Envelope XML creation is the Message object which includes a OnWriteStartElement() method that can be overridden and where the namespaces can be added. But as usually is the case with WCF to get your custom class hooked you have to create several additional classes to get the pipeline to fire your custom handlers.

Leave it to WCF to make this process an exercise in composition hell.  In order to customize the message, three classes are needed:

Message Class
ClientMessageFormatter Class
FormatMessageAttribute Class
You then attach the attribute to each of the Operations in the Service contract interface to get the formatting applied. Most of the code in these classes is just default implementations with a couple of small places where you actually override the default behavior. For the most part this is implement and interface and change the one method that you're interested in.

So here we go – I'll start with the lowest level class that has the implementation and work my way up the stack.

Message Class
First  is the message class implementation which has the actual code that adds the namespaces needed.

 public class RoyalMailCustomMessage : Message
    {
        private readonly Message message;
        public RoyalMailCustomMessage(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", "http://schemas.xmlsoap.org/soap/envelope/");
        }
        protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
        {
            this.message.WriteBodyContents(writer);
        }
        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");         
        }
    }
The key method is OnWriteStartEnvelope() which receives an XmlWriter that you can use to explicitly create the header element. As you can see I add all the namespaces I need in the header here.

Note that you may have to have multiple message classes if various methods use different namespaces. Lucky for me the service I'm dealing with has only a couple of namespaces that are used for all the service methods so a single overload was all we needed for the methods we called on the service.

ClientMessageFormatter

WCF has two kinds of MessageFormatters: ClientMessageFormatter used for client proxy requests and DispatchMessageFormatter which is used for generating server side messages. So if you need to create custom messages for services use a DispatchMessageFormatter which has slightly different overloads than the ones shown here.

Here's the implementation of the ClientMessageFormatter I used:This code basically overrides the SerializeRequest() method and serializes the new message object we created that includes the overridden namespace inclusions.

public class RoyalMailMessageFormatter : IClientMessageFormatter
{
    private readonly IClientMessageFormatter formatter;
    public RoyalMailMessageFormatter(IClientMessageFormatter formatter)
    {
        this.formatter = formatter;
    }
    public Message SerializeRequest(MessageVersion messageVersion, object[] parameters)
    {
        var message = this.formatter.SerializeRequest(messageVersion, parameters);
        return new RoyalMailCustomMessage(message);
    }
    public object DeserializeReply(Message message, object[] parameters)
    {
        return this.formatter.DeserializeReply(message, parameters);
    }
}

FormatMessageAttribute


Finally we also need an attribute to hook up the new formatter to the actual service, which is done by attaching an attribute to the Service Operation on the contract. First you implement the attribute to attach the Formatter.

[AttributeUsage(AttributeTargets.Method)]
public class RoyalMailFormatMessageAttribute : Attribute, IOperationBehavior
{
    public void AddBindingParameters(OperationDescription operationDescription,
        BindingParameterCollection bindingParameters)
    { }
    public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)
    {
        var serializerBehavior = operationDescription.Behaviors.Find<XmlSerializerOperationBehavior>();
        if (clientOperation.Formatter == null)
            ((IOperationBehavior)serializerBehavior).ApplyClientBehavior(operationDescription, clientOperation);
       
        IClientMessageFormatter innerClientFormatter = clientOperation.Formatter;
        clientOperation.Formatter = new RoyalMailMessageFormatter(innerClientFormatter);
    }
    public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
    { }
    public void Validate(OperationDescription operationDescription) { }
}
Here I hook up the custom formatter to the operation.

Note that this service uses XmlSerializer messages and because of that I look for the XmlSerializerOperationBehavior to find the behavior. In other cases you may have to use DataContractSerializerBehavior so be sure to step through the code to see which serializer is registered for the service/operation.

That's a lot of freaking ceremony for essentially 10 lines of code that actually do what we need it to do – but at the same time it's pretty amazing that you get that level of control to hook into the process at such a low level. WCF never fails to shock and awe at the same time :-)

Hooking up the Attribute to Service Operations
When all of the ceremony is done the last thing left to do is to attach the behaviors to the operation contracts. In my case I'm using a WCF generated proxy so I do this in the generated Reference.cs file in the ServiceReferences folder (with show all files enabled):

[System.ServiceModel.OperationContractAttribute(Action="cancelShipment", ReplyAction="*")]
[System.ServiceModel.FaultContractAttribute(typeof(MarvelPress.Workflow.Business.RoyalShippingApi.exceptionDetails),
   Action="cancelShipment", Name="exceptionDetails")]
[System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults=true)]
[System.ServiceModel.ServiceKnownTypeAttribute(typeof(contactMechanism))]
[System.ServiceModel.ServiceKnownTypeAttribute(typeof(baseRequest))]
[RoyalMailFormatMessage]
cancelShipmentResponse1 cancelShipment(MarvelPress.Workflow.Business.RoyalShippingApi.cancelShipmentRequest1 request);
And that's it – I'm now able to run my cancelShipment call against the service and make the request go through.

The new output generated includes all the namespaces at the top of the document (except for the SoapHeader which is generated separately and apparently *can* contain embedded namespaces):

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
                  xmlns:v1="http://www.royalmailgroup.com/integration/core/V1"
                  xmlns:v2="http://www.royalmailgroup.com/api/ship/V2"
                  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                  xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <s:Header xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <h:Security>
    </h:Security>
  </s:Header>
  <soapenv:Body>
    <v2:cancelShipmentRequest>
      <v2:integrationHeader>
        <v1:dateTime>2016-04-02T07:54:34.9402872Z</v1:dateTime>
        <v1:version>2</v1:version>
        <v1:identification>
          <v1:applicationId>RMG-API-G-01</v1:applicationId>
          <v1:transactionId>he3q6qmer3tv</v1:transactionId>
        </v1:identification>
      </v2:integrationHeader>
      <v2:cancelShipments>
        <v2:shipmentNumber>TTT001908905GB</v2:shipmentNumber>
      </v2:cancelShipments>
    </v2:cancelShipmentRequest>
  </soapenv:Body>
</soapenv:Envelope>
And that puts me back in business. Yay!

A generic [EnvelopeNamespaces] Operation Attribute
The implementation above is specific to the service I was connecting to, but I figured it would be nice to make this actually a bit more generic, by letting you configure the namespaces you want to provide for each method. This will make it easier to work with service that might have different namespace requirements for different messages. So rather than having hard coded namespaces in the Message implementation, it would be nice to actually pass an array of namespace strings.

To do this I created a new set of classes that generically allow an array of strings to be attached.

The result is the [EnvelopeNamespaces] Attribute which you can use by explicitly adding namespaces like this using delimited strings in an array:

// CODEGEN: Generating message contract since the operation cancelShipment is neither RPC nor document wrapped.
[System.ServiceModel.OperationContractAttribute(Action="cancelShipment", ReplyAction="*")]
[System.ServiceModel.FaultContractAttribute(typeof(MarvelPress.Workflow.Business.RoyalShippingApi.exceptionDetails), Action="cancelShipment", Name="exceptionDetails")]
[System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults=true)]
[System.ServiceModel.ServiceKnownTypeAttribute(typeof(contactMechanism))]
[System.ServiceModel.ServiceKnownTypeAttribute(typeof(baseRequest))]
[EnvelopeNamespaces(EnvelopeNamespaces = new string[] {
    "v1:http://www.royalmailgroup.com/integration/core/V1",
    "v2:http://www.royalmailgroup.com/api/ship/V2",
    "xsi:http://www.w3.org/2001/XMLSchema-instance",
    "xsd:http://www.w3.org/2001/XMLSchema"
} )]
cancelShipmentResponse1 cancelShipment(MarvelPress.Workflow.Business.RoyalShippingApi.cancelShipmentRequest1 request);     
Here's the more generic implementation:

public class EnvelopeNamespaceMessage : Message
{
    private readonly Message message;
    public string[] EnvelopeNamespaces { get; set; }
    public EnvelopeNamespaceMessage(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", "http://schemas.xmlsoap.org/soap/envelope/");
    }
    protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
    {
        this.message.WriteBodyContents(writer);
    }
    protected override void OnWriteStartEnvelope(XmlDictionaryWriter writer)
    {
        writer.WriteStartElement("soapenv", "Envelope", "http://schemas.xmlsoap.org/soap/envelope/");
        if (EnvelopeNamespaces != null)
        {
            foreach (string ns in EnvelopeNamespaces)
            {
                var tokens = ns.Split(new char[] {':'}, 2);
                writer.WriteAttributeString("xmlns", tokens[0], null, tokens[1]);
            }
        }
    }
}
public class EnvelopeNamespaceMessageFormatter : IClientMessageFormatter
{
    private readonly IClientMessageFormatter formatter;
    public string[] EnvelopeNamespaces { get; set; }
    public EnvelopeNamespaceMessageFormatter(IClientMessageFormatter formatter)
    {
        this.formatter = formatter;
    }
    public Message SerializeRequest(MessageVersion messageVersion, object[] parameters)
    {
        var message = this.formatter.SerializeRequest(messageVersion, parameters);
        return new EnvelopeNamespaceMessage(message) {EnvelopeNamespaces = EnvelopeNamespaces};
    }
    public object DeserializeReply(Message message, object[] parameters)
    {
        return this.formatter.DeserializeReply(message, parameters);
    }
}

[AttributeUsage(AttributeTargets.Method)]
public class EnvelopeNamespacesAttribute : Attribute, IOperationBehavior
{
    public string[] EnvelopeNamespaces { get; set; }
    public void AddBindingParameters(OperationDescription operationDescription,
        BindingParameterCollection bindingParameters)
    {
    }
    public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)
    {
            //var serializerBehavior = operationDescription.Behaviors.Find<DataContractSerializerOperationBehavior>();
            IOperationBehavior serializerBehavior = operationDescription.Behaviors.Find<XmlSerializerOperationBehavior>();
            if (serializerBehavior == null)
                serializerBehavior = operationDescription.Behaviors.Find<DataContractSerializerOperationBehavior>() ;
            if (clientOperation.Formatter == null)
                serializerBehavior.ApplyClientBehavior(operationDescription, clientOperation);
        IClientMessageFormatter innerClientFormatter = clientOperation.Formatter;
        clientOperation.Formatter = new EnvelopeNamespaceMessageFormatter(innerClientFormatter)
        {
            EnvelopeNamespaces = EnvelopeNamespaces
        };
    }
    public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
    {
    }
    public void Validate(OperationDescription operationDescription)
    {
    }
}
Summary
Ah, WCF == (love && hate).

You gotta love that you can hook into the pipeline and fix a problem like this and that the designers thought of millions of intricate ways to manage the process of manipulating messages. But man is this stuff difficult to discover this stuff or even to hook it up. I was lucky I found a reference to MessageFormatter in an obscure post referenced in a comment.

While the code to actually do the work is really simple there is a boat load of ceremony around all of this code to get it to actually fire. Plus an attribute has to be added to each and every Operation method and it also means I have to manually edit the generated WCF proxy Client interface. All of which is as far from 'transparent' as you can get.

But hey, at least I managed to get it to work and now we can get on with our lives actually talking to the service. I shudder to think what other lovely oddities we might run into with this service, but I leave that for another day.

I hope this information is useful to some of you, although I hope even more that you won't need it, because you know, you shouldn't have to do it this way! But as is often the case, we can't always choose what crappy services we have to  interact with on the server and workarounds are what we have to work with.

So I hope this has been useful… I know my previous posts on WCF formatting issues are among the most popular on this blog. Heck, I have a feeling I'll be revisiting this post myself in the not so distant future since problem SOAP services are a never-ending plague these days…

Create a Basic WCF Web HTTP Service


Windows Communication Foundation (WCF) allows you to create a service that exposes a Web endpoint. Web endpoints send data by XML or JSON, there is no SOAP envelope. This topic demonstrates how to expose such an endpoint.
Note
The only way to secure a Web endpoint is to expose it through HTTPS, using transport security. When using message-based security, security information is usually placed in SOAP headers and because the messages sent to non-SOAP endpoints contain no SOAP envelope, there is nowhere to place the security information and you must rely on transport security.

To create a Web endpoint

  1. Define a service contract using an interface marked with the ServiceContractAttributeWebInvokeAttribute and the WebGetAttribute attributes.
    C#
    [ServiceContract]
    public interface IService
    {
        [OperationContract]
        [WebGet]
        string EchoWithGet(string s);
    
        [OperationContract]
        [WebInvoke]
        string EchoWithPost(string s);
    }
    
    Note
    By default, WebInvokeAttribute maps POST calls to the operation. You can, however, specify the HTTP method (for example, HEAD, PUT, or DELETE) to map to the operation by specifying a "method=" parameter. WebGetAttribute does not have a "method=" parameter and only maps GET calls to the service operation.
  2. Implement the service contract.
    C#
    public class Service : IService
    {
        public string EchoWithGet(string s)
        {
            return "You said " + s;
        }
    
        public string EchoWithPost(string s)
        {
            return "You said " + s;
        }
    }
    

To host the service

  1. Create a WebServiceHost object.
    C#
    WebServiceHost host = new WebServiceHost(typeof(Service), new Uri("http://localhost:8000/"));
    
  2. Add a ServiceEndpoint with the WebHttpBehavior.
    C#
    ServiceEndpoint ep = host.AddServiceEndpoint(typeof(IService), new WebHttpBinding(), "");
    
    Note
    If you do not add an endpoint, WebServiceHost automatically creates a default endpoint. WebServiceHost also adds WebHttpBehavior and disables the HTTP Help page and the Web Services Description Language (WSDL) GET functionality so the metadata endpoint does not interfere with the default HTTP endpoint.
    Adding a non-SOAP endpoint with a URL of "" causes unexpected behavior when an attempt is made to call an operation on the endpoint. The reason for this is the listen URI of the endpoint is the same as the URI for the help page (the page that is displayed when you browse to the base address of a WCF service).
    You can do one of the following actions to prevent this from happening:
    • Always specify a non-blank URI for a non-SOAP endpoint.
    • Turn off the help page. This can be done with the following code.
    C#
    ServiceDebugBehavior sdb = host.Description.Behaviors.Find<ServiceDebugBehavior>();
    sdb.HttpHelpPageEnabled = false;
    
  3. Open the service host and wait until the user presses ENTER.
    C#
    host.Open();
    Console.WriteLine("Service is running");
    Console.WriteLine("Press enter to quit...");
    Console.ReadLine();
    host.Close();
    
    This sample demonstrates how to host a Web-Style service with a console application. You can also host such a service within IIS. To do this, specify the WebServiceHostFactory class in a .svc file as the following code demonstrates.
          <%ServiceHost   
    language=c#  
    Debug="true"  
    Service="Microsoft.Samples.Service"  
    Factory=System.ServiceModel.Activation.WebServiceHostFactory%>  
    

To call service operations mapped to GET in Internet Explorer

  1. Open Internet Explorer and type "http://localhost:8000/EchoWithGet?s=Hello, world!" and press ENTER. The URL contains the base address of the service ("http://localhost:8000/"), the relative address of the endpoint (""), the service operation to call ("EchoWithGet"), and a question mark followed by a list of named parameters separated by an ampersand (&).

To call service operations in code

  1. Create an instance of System.ServiceModel.Web.WebChannelFactory within a using block.
    C#
    using (ChannelFactory<IService> cf = new ChannelFactory<IService>(new WebHttpBinding(), "http://localhost:8000"))
    
  2. Add WebHttpBehavior to the endpoint the ChannelFactory calls.
    C#
    cf.Endpoint.Behaviors.Add(new WebHttpBehavior());
    
  3. Create the channel and call the service.
    C#
    IService channel = cf.CreateChannel();
    
    string s;
    
    Console.WriteLine("Calling EchoWithGet via HTTP GET: ");
    s = channel.EchoWithGet("Hello, world");
    Console.WriteLine("   Output: {0}", s);
    
    Console.WriteLine("");
    Console.WriteLine("This can also be accomplished by navigating to");
    Console.WriteLine("http://localhost:8000/EchoWithGet?s=Hello, world!");
    Console.WriteLine("in a web browser while this sample is running.");
    
    Console.WriteLine("");
    
    Console.WriteLine("Calling EchoWithPost via HTTP POST: ");
    s = channel.EchoWithPost("Hello, world");
    Console.WriteLine("   Output: {0}", s);
    
  4. Close the WebServiceHost.
    C#
    host.Close();
    

Example

The following is the full code listing for this example.
C#
// Service.cs
using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Web;
using System.Text;

namespace Microsoft.ServiceModel.Samples.BasicWebProgramming
{
    [ServiceContract]
    public interface IService
    {
        [OperationContract]
        [WebGet]
        string EchoWithGet(string s);

        [OperationContract]
        [WebInvoke]
        string EchoWithPost(string s);
    }
    public class Service : IService
    {
        public string EchoWithGet(string s)
        {
            return "You said " + s;
        }

        public string EchoWithPost(string s)
        {
            return "You said " + s;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            WebServiceHost host = new WebServiceHost(typeof(Service), new Uri("http://localhost:8000/"));
            try
            {
                ServiceEndpoint ep = host.AddServiceEndpoint(typeof(IService), new WebHttpBinding(), "");
                host.Open();
                using (ChannelFactory<IService> cf = new ChannelFactory<IService>(new WebHttpBinding(), "http://localhost:8000"))
                {
                    cf.Endpoint.Behaviors.Add(new WebHttpBehavior());
                    
                    IService channel = cf.CreateChannel();

                    string s;

                    Console.WriteLine("Calling EchoWithGet via HTTP GET: ");
                    s = channel.EchoWithGet("Hello, world");
                    Console.WriteLine("   Output: {0}", s);

                    Console.WriteLine("");
                    Console.WriteLine("This can also be accomplished by navigating to");
                    Console.WriteLine("http://localhost:8000/EchoWithGet?s=Hello, world!");
                    Console.WriteLine("in a web browser while this sample is running.");

                    Console.WriteLine("");

                    Console.WriteLine("Calling EchoWithPost via HTTP POST: ");
                    s = channel.EchoWithPost("Hello, world");
                    Console.WriteLine("   Output: {0}", s);
                    Console.WriteLine("");
                }

                Console.WriteLine("Press <ENTER> to terminate");
                Console.ReadLine();
                
                host.Close();
            }
            catch (CommunicationException cex)
            {
                Console.WriteLine("An exception occurred: {0}", cex.Message);
                host.Abort();
            }
        }
    }
}

Compiling the Code

When compiling Service.cs reference System.ServiceModel.dll and System.ServiceModel.Web.dll.