C# – WCF input huge XML as Stream with Content-Type: xml/text

cwcf

I have a RESTful WCF web service that processes huge XML files that are passed in as a Stream with a Header Content-Type: text/text using a POST method. When a client tries to use this web service with a Header Content-Type: text/xml, they receive a "…contains an unrecognized http body format value 'Xml'. The expected body format value is 'Raw'. This can be because a WebContentTypeMapper has not been configured on the binding" error.
I am tasked with making this web service work with a Header Content-Type:text/xml as a multitude of clients use this web services with other services and do not want to change the content type just for this service. How do I map the incoming Stream as WebContentFormat.Raw and get this web service to accept the Content-Type:text/xml?
Thank you.

Best Answer

I solved this issue by creating a new class that derives from WebContentTypeMapper and changing the WebContentFormat to 'Raw' when the Content-Type = 'text/xml'. Along with this new class, I updated the web.config to use the 'customBinding' element under 'bindings'.

public class XmlContentTypeMapper : WebContentTypeMapper
{
    public override WebContentFormat
               GetMessageFormatForContentType(string contentType)
    {
        if (contentType.Contains("text/xml") ||  contentType.Contains("application/xml"))
        {
            return WebContentFormat.Raw;
        }
        else
        {
            return WebContentFormat.Default;
        }
    }
}

web.config

<bindings>
  <customBinding>
    <binding name="XmlMapper">
      <webMessageEncoding webContentTypeMapperType="Lt.Trigger.XmlContentTypeMapper, ExService" />
      <httpTransport manualAddressing="true" />
    </binding>
  </customBinding>
</bindings>
Related Topic