WCF Web API 轻松实现 REST

先体验一下,如果没有 WCF Web API,直接用 WCF 实现 REST 有多麻烦:

1. 创建 WCF 服务(ServiceContract)。

2. 创建 .svc 文件指向该 WCF 服务。

3. 在 web.config 中添加 <service>/<endpoint> 配置,并将 binding 设置为 webHttpBinding,示例配置如下:

<services>
<service name="CNBlogs.OpenAPI.Service.NewsRestService">
<endpoint binding="webHttpBinding"
contract
="CNBlogs.OpenAPI.Service.INewsRestService"
behaviorConfiguration
="RESTFul"/>
</service>
</services>

4. 在 web.config 中添加 <endpointBehaviors>/<behavior> 配置,并在其中添加<webHttp />,在第3步的配置中添加该behaviorConfiguration(比如上面代码中的behaviorConfiguration="RESTFul"),示例配置如下:

<endpointBehaviors>
<behavior name="RESTFul">
<webHttp />
</behavior>
</endpointBehaviors>

5. 在 OperationContract 方法上增加 WebInvoke 属性,示例代码如下:

[OperationContract]
[WebInvoke(Method = "GET",
UriTemplate = "News/Recent/{itemcount}",
ResponseFormat = WebMessageFormat.Xml)
]
IQueryable<NewsItem> GetRecentNews(int itemcount);

上面的5步已经够麻烦了。开始以为到此就可以收工了,哪知不运行不知道,一运行吓一跳:

Operation 'GetRecentNews' in contract 'INewsRestService' has a path variable named 'itemcount' which does not have type 'string'.  
Variables for UriTemplate path segments must have type 'string'.

参数竟然不能用int类型,必须要用 string。只能望 WCF 心叹,不得不进入第6步。

6. 将 int 改为 string

IQueryable<NewsItem> GetRecentNews(string itemcount);

这是纯 WCF 实现 REST 的表演节目,节目名称叫“ WCF 实现 REST 六步走”,表演得分6分。

 

接下来,我们看看 WCF Web API 的表演

(如果不知道 WCF Web API 是何方神圣,请看演员介绍http://wcf.codeplex.com/wikipage?title=WCF%20HTTP

1. 在提供 REST 服务的方法上增加 [WebGet(UriTemplate = "")] 属性,示例代码如下:

[ServiceContract]
public class NewsRestService
{
[WebGet(UriTemplate = "{itemcount}")]
public IQueryable<NewsItem> GetRecentNews(int itemcount)
{
return newsList.AsQueryable();
}
}

2. 在 Global.asax 的 Application_Start 中添加路由,示例代码如下:

protected void Application_Start(object sender, EventArgs e)
{
var config = new HttpConfiguration() ;
RouteTable.Routes.Add(new ServiceRoute("news/recent",
new HttpServiceHostFactory { Configuration = config },
typeof(NewsRestService)));
}

注:需要通过 NuGet 添加对 WebApi.All 的引用。news/recent 就是 REST 访问网址。

(注2:如果出现“ASP.NET routing integration feature requires ASP.NET compatibility.”错误,请在web.config中加上<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>)

收工!只需两步就实现 REST,WCF Web API 的表演得分2分。

2 : 6,WCF Web API 大获全胜!(分数少的怎么反而获胜?这是代码世界,不是现实世界,程序员说了算,谁的代码少,谁就获胜)


小结

WCF Web API 是 “First-class programming model for HTTP in WCF”,而 HTTP 是 Web 世界的通行证,Web API 可以让我们更轻松地畅游于 Web 编程世界。

实现 REST 只是 WCF Web API 小试牛刀,我们还可以不用修改任何服务端代码,只改变客户端请求的方式,就可以返回不现类型的数据。

比如:

1)将 HTTP Header 中的 Accept 改为 “application/json”,返回的就是 JSON 数据。

2)通过 Url 参数发起 OData 查询(比如“?$top=4&$orderby=Title” ),服务器收到请求后,会对返回结果进行 LINQ 查询(因此示例代码中的返回值类型是IQueryable<NewsItem>)。


相关内容

英文:

WCF Web API Overview

Getting Started: Building a simple Web API

WCF Web APIs, HTTP your way

中文:

WCF Web API 第一印象

WCF Web Api

入门:构建简单的Web API

入门:添加一个支持获取单一资源以及支持POST,PUT和DELETE方法

posted @ 2011-10-27 14:08  dudu  阅读(16148)  评论(20编辑  收藏  举报