WCF WebInvoke which can accept content-type: text/plain?

Deadly 提交于 2019-12-05 11:51:38

You can fix this, as the error message indicates, by creating and applying a custom WebContentTypeMapper. It should look like this:

namespace StackOverflow36216464
{
    public class RawContentTypeMapper : WebContentTypeMapper
    {
        public override WebContentFormat GetMessageFormatForContentType(string contentType)
        {
            switch (contentType.ToLowerInvariant())
            {
                case "text/plain":
                case "application/json":
                    return WebContentFormat.Json;
                case "application/xml":
                    return WebContentFormat.Xml;
                default:
                    return WebContentFormat.Default;
            }
        }
    }
}

This one interprets the content-type of the request, and returns the appropriate WebContentFormat enum member.

You can then apply it to your service in the form of a custom binding:

<system.serviceModel>
    <bindings>
        <customBinding>
            <binding name="textPlainToApplicationJson">
                <webMessageEncoding webContentTypeMapperType="StackOverflow36216464.RawContentTypeMapper, StackOverflow36216464, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
                <httpTransport manualAddressing="true" />
            </binding>
        </customBinding>
    </bindings>
    <behaviors>
        <serviceBehaviors>
            <behavior name="debugServiceBehavior">
                <serviceDebug includeExceptionDetailInFaults="true" />
            </behavior>
        </serviceBehaviors>
        <endpointBehaviors>
            <behavior name="restEndpointBehavior">
                <webHttp />
            </behavior>
        </endpointBehaviors>
    </behaviors>
    <services>
        <service
          name="StackOverflow36216464.Service1"
          behaviorConfiguration="debugServiceBehavior">
            <host>
                <baseAddresses>
                    <add baseAddress="http://localhost:65393/"/>
                </baseAddresses>
            </host>
            <endpoint address=""
                  binding="customBinding"
                  contract="StackOverflow36216464.IService1"
                  behaviorConfiguration="restEndpointBehavior"
                  bindingConfiguration="textPlainToApplicationJson"/>        
        </service>
    </services>
</system.serviceModel>

The relevant part being the <customBinding> element, where the custom mapper is configured, and the servcices/service/endpoint/bindingConfiguration attribute where it is applied.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!