WCF 为内容类型提供一组默认的映射。例如,application/json 映射到 JSON,text/xml 映射到 XML。未映射到 JSON 或 XML 的任何内容类型都将映射到原始二进制格式。
在某些方案(例如推送式 API)中,服务开发人员不控制由客户端返回的内容类型。例如,客户端可以将 JSON 作为 text/javascript 而不是 application/json 返回。在这种情况下,服务开发人员必须提供从 WebContentTypeMapper 派生的类型以正确处理给定的内容类型,如下面的示例代码所示。
public class JsonContentTypeMapper : WebContentTypeMapper { public override WebContentFormat GetMessageFormatForContentType(string contentType) { if (contentType == "text/javascript") { return WebContentFormat.Json; } else { return WebContentFormat.Default; } } }
该类型必须重写 GetMessageFormatForContentType 方法。该方法必须计算 contentType 参数并返回下列值之一:Json、Xml、Raw 或 Default。返回 Default 时将遵从默认的 Web 消息编码器映射。在前面的示例代码中,text/javascript 内容类型映射到 JSON,所有其他映射保持不变。
若要使用 JsonContentTypeMapper 类,终结点必须使用自定义绑定。
<customBinding> <binding name="JsonMapper"> <webMessageEncoding webContentTypeMapperType= "Microsoft.Ajax.Samples.JsonContentTypeMapper, JsonContentTypeMapper, Version=3.5.0.0, Culture=neutral, PublicKeyToken=null" /> <httpTransport manualAddressing="true" /> </binding> </customBinding>
若要验证使用 JsonContentTypeMapper 的要求,请在配置文件中仅用 <webMessageEncoding /> 替换前面的 <webMessageEncoding webContentTypeMapperType=。在尝试使用 text/javascript 来发送 JSON 内容时,客户端页加载将失败。