代码改变世界

WCF 第十三章 可编程站点 为站点创建操作

2011-06-03 06:55  DanielWise  阅读(1434)  评论(1编辑  收藏  举报
为站点创建操作是指我们想要基于URIs暴露服务,不使用SOAP来对消息编码,使用HTTP协议传递参数,使用JSON或者POX来格式化数据。WCF提供WebHttpBinding绑定来支持这些特性。WebHttpBinding绑定使用两个绑定元素构建。第一个绑定元素是一个称作WebMessageEncodingBindingElement的新的消息编码器。这是一个允许消息使用JSON或者POX进行编码的新的绑定元素。第二个绑定元素是一个基于HttpTransportBindingElement或者HttpsTransportBindingElement的传输绑定元素。这些绑定元素允许使用HTTP协议进行通信。HttpsTransportBindingElement绑定元素用来支持传输层的安全。
使用WebHttpBinding寄宿
为了检查如何使用WebHttpBinding绑定,我们将创建一个简单的Echo 网络服务。我们将一直保持这个例子简单因为我们将在这一章的后续部分扩展介绍如何使用这个绑定。列表13.3显示了IEchoService接口。接口定义了一个有唯一的称为Echo的操作契约的服务契约。注意Echo操作契约也是用WebGet属性。这个属性告诉WebHttpBinding绑定可以使用GET动词基于HTTP协议暴露这个操作。
列表13.3 IEchoService 接口
    [ServiceContract]
    public interface IEchoService
    {
        [OperationContract]
        [WebGet]
        string Echo(string echoThis);
    }
列表13.4 显示了实现IEchoService接口的EchoService 类。这个类通过接收echoThis参数并将其返回给客户端来实现Echo操作。
列表13.4 EchoService类
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Web;

namespace EchoServiceApp
{
    [ServiceContract]
    public interface IEchoService
    {
        [OperationContract]
        [WebGet]
        string Echo(string echoThis);
    }

    public class EchoService : IEchoService
    {
        public string Echo(string echoThis)
        {
            return string.Format("You sent this '{0}'.", echoThis);
        }
    }
}
  最后要做的是在IIS内寄宿EchoService 服务。列表13.5显示了允许我们使用WebHttpBinding绑定来寄宿服务的配置文件。关键点是WebHttpBinding绑定不确定暴露服务的格式。相反我们需要使用一个终结点行为来确定使用WebHttpBinding绑定暴露的服务返回的格式。需要使用两个终结点行为: WebHttpBehavior和WebScriptEnablingBehavior。WebScriptEnablingBehavior行为将在稍后本章的“使用AJAX和JSON进行网页编程”中讨论。现在我们将讨论WebHttpBehavior行为。WebHttpBehavior终结点行为与WebHttpBinding一起使用来对消息进行JSON或者XML格式化。默认行为是使用XML.
列表13.5 EchoService配置
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.serviceModel>
    <behaviors>
      <endpointBehaviors>
        <behavior name="WebBehavior">
          <webHttp />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <services>
      <service name="EchoServiceApp.EchoService">
        <endpoint address="" behaviorConfiguration="WebBehavior" binding="webHttpBinding" contract="EchoServiceApp.IEchoService" />
      </service>
    </services>
  </system.serviceModel>
</configuration>
  图片13.1 显示了当在WebHttpBinding绑定上暴露EchoService 服务时的输出结果。因为我们使用WebGet属性里暴露服务,我们可以通过在一个浏览器中输入URI地址来调用服务。URI地址是http://localhost/SimpleWebService/EchoService/Echo?echoThis=helloworld.
图片13.1 使用WebHttpBinding绑定在浏览器中的反馈