WCF Web API輕松實(shí)現(xiàn)REST
先體驗(yàn)一下,如果沒有 WCF Web API,直接用 WCF 實(shí)現(xiàn) REST 有多麻煩:
1. 創(chuàng)建 WCF 服務(wù)(ServiceContract)。
2. 創(chuàng)建 .svc 文件指向該 WCF 服務(wù)。
3. 在 web.config 中添加<service>/<endpoint> 
- <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步已經(jīng)夠麻煩了。開始以為到此就可以收工了,哪知不運(yùn)行不知道,一運(yùn)行嚇一跳:
- 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'.
 
參數(shù)竟然不能用int類型,必須要用 string。只能望 WCF 心嘆,不得不進(jìn)入第6步。
6. 將 int 改為 string
 
- IQueryable<NewsItem> GetRecentNews(string itemcount);
 
這是純 WCF 實(shí)現(xiàn) REST 的表演節(jié)目,節(jié)目名稱叫“ WCF 實(shí)現(xiàn) REST 六步走”,表演得分6分。
接下來,我們看看 WCF Web API 的表演
(如果不知道 WCF Web API 是何方神圣,請看演員介紹http://wcf.codeplex.com/wikipage?title=WCF%20HTTP)
1. 在提供 REST 服務(wù)的方法上增加 [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 訪問網(wǎng)址。
收工!只需兩步就實(shí)現(xiàn) REST,WCF Web API 的表演得分2分。
2 : 6,WCF Web API 大獲全勝?。ǚ?jǐn)?shù)少的怎么反而獲勝?這是代碼世界,不是現(xiàn)實(shí)世界,程序員說了算,誰的代碼少,誰就獲勝)
小結(jié)
WCF Web API 是 “First-class programming model for HTTP in WCF”,而 HTTP 是 Web 世界的通行證,Web API 可以讓我們更輕松地暢游于 Web 編程世界。
實(shí)現(xiàn) REST 只是 WCF Web API 小試牛刀,我們還可以不用修改任何服務(wù)端代碼,只改變客戶端請求的方式,就可以返回不現(xiàn)類型的數(shù)據(jù)。
比如:
1)將 HTTP Header 中的 Accept 改為 “application/json”,返回的就是 JSON 數(shù)據(jù)。
2)通過 Url 參數(shù)發(fā)起 OData 查詢(比如“?$top=4&$orderby=Title” ),服務(wù)器收到請求后,會對返回結(jié)果進(jìn)行 LINQ 查詢(因此示例代碼中的返回值類型是IQueryable<NewsItem>)。
原文:http://www.cnblogs.com/dudu/archive/2011/10/27/wcf_web_api.html
【編輯推薦】















 
 
 




 
 
 
 