简单介绍使用WCF的Web编程模型开发REST风格的Web Service

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+rest资料参见:http://msdn.microsoft.com/zh-cn/magazine/dd315413.aspx#id0070078

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值