WebContentTypeMapper 示例演示如何将新内容类型映射到 Windows Communication Foundation (WCF) 消息正文格式。
该 WebHttpEndpoint 元素插入 Web 消息编码器,允许 WCF 在同一终结点接收 JSON、XML 或原始二进制消息。 编码器通过查看请求的 HTTP 内容类型来确定消息的正文格式。 此示例引入了 WebContentTypeMapper 类,该类允许用户控制内容类型和正文格式之间的映射。
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(String) 方法。 该方法必须计算contentType
参数并返回以下值之一:Json、Xml、或RawDefault。 返回 Default 时将遵从默认的 Web 消息编码器映射。 在前面的示例代码中, text/javascript
内容类型映射到 JSON,所有其他映射保持不变。
若要使用该 JsonContentTypeMapper
类,请在 Web.config中使用以下内容:
<system.serviceModel>
<standardEndpoints>
<webHttpEndpoint>
<standardEndpoint name="" contentTypeMapper="Microsoft.Samples.WebContentTypeMapper.JsonContentTypeMapper, JsonContentTypeMapper, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>
若要验证使用 JsonContentTypeMapper 的要求,请从上述配置文件中删除 contentTypeMapper 属性。 尝试用于 text/javascript
发送 JSON 内容时,客户端页无法加载。
设置、生成和运行示例
确保已为 Windows Communication Foundation 示例 执行One-Time 安装过程。
生成解决方案WebContentTypeMapperSample.sln,如 生成 Windows Communication Foundation 示例中所述。
导航到
http://localhost/ServiceModelSamples/JCTMClientPage.htm
(不要在浏览器中从项目目录中打开 JCTMClientPage.htm)。