如何:向 SOAP 和 Web 客户端公开协定

默认情况下,Windows Communication Foundation (WCF) 使终结点只可用于 SOAP 客户端。在如何:创建基本 Web 样式服务中,非 SOAP 客户端可以使用终结点。有时可能需要使相同的协定可以同时作为 Web 终结点和 SOAP 终结点使用。本主题演示了如何实现此目的的示例。

定义服务协定

  1. 使用以 ServiceContractAttribute, WebInvokeAttributeWebGetAttribute 属性标记的接口来定义服务协定。

    提示

    默认情况下,WebInvokeAttribute 将 POST 调用映射到操作。不过,可以指定“method=”参数来指定映射到操作的方法。WebGetAttribute 没有“method=”参数并且仅将 GET 调用映射到服务操作。

  2. 实现服务协定。

承载服务

  1. 创建一个 ServiceHost 对象。

  2. 为 SOAP 终结点添加一个具有 BasicHttpBindingServiceEndpoint

  3. 为非 SOAP 终结点添加一个具有 WebHttpBindingServiceEndpoint,并将 WebHttpBehavior 添加到该终结点。

  4. ServiceHost 实例上调用 Open() 以打开服务主机。

在 Internet Explorer 中调用映射到 GET 的服务操作

  1. 打开 Internet Explorer 并键入“https://localhost:8000/EchoWithGet?s=Hello, world!”,然后按 Enter。该 URL 包含服务的基址 ("https://localhost:8000/")、终结点的相对地址 ("")、要调用的服务操作 ("EchoWithGet")、一个问号以及其后通过“and”符号 (&) 分隔的命名参数的列表。

使用代码在 Web 终结点上调用服务操作

  1. 创建 using 块内的 WebChannelFactory 的实例。

提示

将在 using 块的末尾处的通道上自动调用 Close()。

  1. 创建通道并调用服务。

在 SOAP 终结点上调用服务操作

  1. 创建 using 块内的 ChannelFactory 的实例。

  2. 创建通道并调用服务。

关闭服务主机

  1. 关闭服务主机。

示例

下面列出了此主题的完整代码。

编译代码

编译 Service.cs 时,请参考 System.ServiceModel.dll 和 System.ServiceModel.Web.dll。

另请参见

参考

WebHttpBinding
WebGetAttribute
WebInvokeAttribute
WebServiceHost
ChannelFactory
WebHttpBehavior