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相关知识,可以参考这篇论文

 posted on 2008-01-10 01:01  紫色阴影  阅读(3979)  评论(9编辑  收藏  举报
我要啦免费统计