使用WCF的Web编程模型开发REST风格的Web Service

文/blusehuang  出处/博客园

  WCF中的Web编程模型提供了一种以REST风格来设计Web Service的功能,它不同于以往基于SOAP或者WS-*规范的Web Service,而是以URI和http协议为中心的。对于操作的每一个资源有唯一的标志符,而利用不同的http动作(例如GET,POST,PUT,DELETE)来对这些资源进行相应的操作。同时该模型中还提供URI Template,它是用来定义参数化的URI,使URI的某些部分作为参数在服务中使用。可能这样解释十分含糊不清,下面用一个小例子来说明这种Web编程模型。

  在该例子中,我们使用Northwind数据库,.NET Framework 3.5,开发工具我使用的是VS2005.

  首先我们实现一个简单的需求,就是能够获取所有的Customers,这样我们定义一个Customer的Service Contract,其中包括名为GetAllCustomers的Operation Contract。

  [ServiceContract]
  public interface ICustomerService
  {
      [OperationContract]
      [WebGet(UriTemplate = "")]
      List<Customer> GetAllCustomers();
  }

可以看到,这是WCF中一个标准Service Contract的定义,其中的WebGet属性可能是以前没有见过的,它表示该服务是用Get动作来获取数据,UriTemplate为空字符串表示它不匹配任何参数。

接下来我们实现这个Service,使之从数据库中的Customer表读取所有数据,这里的Customer是一个Data Contract。

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class CustomerService : ICustomerService
{
    public List<Customer> GetAllCustomers()
    {
        List<Customer> customerList = new List<Customer>();

        //.........从数据库中获得所有的Customer

        return customerList;
    }
}

这样,服务已经定义好并且有了实际的实现,以及我们应该用Get方法来访问这个服务,最后,该服务需要被发布出来以让外界访问。

ICustomerService customerService = new CustomerService();
WebServiceHost customerServiceHost
    = new WebServiceHost(customerService, new Uri("http://localhost:3333/"));
customerServiceHost.AddServiceEndpoint(typeof (ICustomerService), new WebHttpBinding(), "customers");
customerServiceHost.Open();

在浏览器中敲入http://localhost:3333/customers,返回的是以xml格式来描述的所有customers。

如果我们想根据CustomerID来查询某一个Customer,需要在Service Contract中增加一个Operation Contract。

[OperationContract]
[WebGet(UriTemplate = "{customerID}")]
Customer GetCustomer(string customerID);

这里的customerID是参数,如果访问的URI是http://localhost:3333/customers/ALFKI,那么customerID匹配的就是ALFKI。

接下来便实现该Operation Contract,当我们在浏览器中敲入http://localhost:3333/customers/ALFKI,返回的是xml格式描述的ALFKI这个Customer的信息。

本文主要介绍如何使用WCF的Web编程模型来开发REST风格的Web Service,在接下来的文章中会介绍更多的相关内容,比如复杂的UriTemplate、POST/PUT/DELETE的http动作等。如果想了解REST相关知识,可以参考这篇论文

 感谢原创者的辛勤劳动,希望对您有所帮助,转载请注明原出处。
 您可能对 [Web Service] 的这些文章也感兴趣:

ASP.NET创建Web服务之使用事务  Web Service 安全性解决方案(SOAP篇)
ASP.NET服务器端异步Web方法  Javascript调用Webservice的汇集
页面前台通过JS访问WEB SERVICES,以及如何处理返回结果  ASP.NET创建Web服务之发布和部署
Amazon宣布AWS挑战优胜者  ASP.NET创建Web服务之XML基础结构
创建数据库Web Services  实现Web Service依赖倒置
定义web service接口的十点注意事项  ASP.NET创建Web服务之管理Web服务状态
SharePoint Web Services入门  有了Web Service,还需要.NET吗?
ASP.NET创建Web服务之设计方针  XML Web Service 安全性
客户端访问Web Service方法的一个细节  创建数据库Web Services
如何创建和使用Web服务  利用Web Services保持Http环境下的连接状态