WebContentTypeMapper 示例

本示例演示如何将新内容类型映射到 Windows Communication Foundation (WCF) 消息正文格式。

提示

此示例需要安装 .NET Framework 3.5 版才能生成和运行。若要打开项目和解决方案文件,需要使用 Visual Studio 2008。

<webHttpBinding> 元素可插入 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 方法。该方法必须计算 contentType 参数并返回下列值之一:JsonXmlRawDefault。返回 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 内容时,客户端页加载将失败。

设置、生成和运行示例

  1. 请确保已经执行了 Windows Communication Foundation 示例的一次性安装过程

  2. 按照生成 Windows Communication Foundation 示例中的说明生成解决方案 WebContentTypeMapperSample.sln。

  3. 定位到 https://localhost/ServiceModelSamples/JCTMClientPage.htm(不要在浏览器中从项目目录中打开 JCTMClientPage.htm)。

Send comments about this topic to Microsoft.
© 2007 Microsoft Corporation. All rights reserved.