新聞中心
先體驗一下,如果沒有 WCF Web API,直接用 WCF 實現(xiàn) REST 有多麻煩:

沿河網(wǎng)站建設公司創(chuàng)新互聯(lián),沿河網(wǎng)站設計制作,有大型網(wǎng)站制作公司豐富經(jīng)驗。已為沿河千余家提供企業(yè)網(wǎng)站建設服務。企業(yè)網(wǎng)站搭建\成都外貿(mào)網(wǎng)站建設要多少錢,請找那個售后服務好的沿河做網(wǎng)站的公司定做!
1. 創(chuàng)建 WCF 服務(ServiceContract)。
2. 創(chuàng)建 .svc 文件指向該 WCF 服務。
3. 在 web.config 中添加
- contract="CNBlogs.OpenAPI.Service.INewsRestService"
- behaviorConfiguration="RESTFul" />
4. 在 web.config 中添加
5. 在 OperationContract 方法上增加 WebInvoke 屬性,示例代碼如下:
- [OperationContract]
- [WebInvoke(Method = "GET",
- UriTemplate = "News/Recent/{itemcount}",
- ResponseFormat = WebMessageFormat.Xml)
- ]
- IQueryable
GetRecentNews(int itemcount);
上面的5步已經(jīng)夠麻煩了。開始以為到此就可以收工了,哪知不運行不知道,一運行嚇一跳:
- 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 心嘆,不得不進入第6步。
6. 將 int 改為 string
- IQueryable
GetRecentNews(string itemcount);
這是純 WCF 實現(xiàn) REST 的表演節(jié)目,節(jié)目名稱叫“ WCF 實現(xiàn) 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
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)址。
收工!只需兩步就實現(xiàn) REST,WCF Web API 的表演得分2分。
2 : 6,WCF Web API 大獲全勝?。ǚ謹?shù)少的怎么反而獲勝?這是代碼世界,不是現(xiàn)實世界,程序員說了算,誰的代碼少,誰就獲勝)
小結(jié)
WCF Web API 是 “First-class programming model for HTTP in WCF”,而 HTTP 是 Web 世界的通行證,Web API 可以讓我們更輕松地暢游于 Web 編程世界。
實現(xiàn) REST 只是 WCF Web API 小試牛刀,我們還可以不用修改任何服務端代碼,只改變客戶端請求的方式,就可以返回不現(xiàn)類型的數(shù)據(jù)。
比如:
1)將 HTTP Header 中的 Accept 改為 “application/json”,返回的就是 JSON 數(shù)據(jù)。
2)通過 Url 參數(shù)發(fā)起 OData 查詢(比如“?$top=4&$orderby=Title” ),服務器收到請求后,會對返回結(jié)果進行 LINQ 查詢(因此示例代碼中的返回值類型是IQueryable
原文:http://www.cnblogs.com/dudu/archive/2011/10/27/wcf_web_api.html
【編輯推薦】
- 百度地圖API之如何制作公交導航
- 走進Windows線程同步API
- 谷歌拼音輸入法擴展API開發(fā)指南
- 新浪微博API開發(fā)簡介之用戶授權(quán)(PHP基礎篇)
- 百度地圖API開發(fā)指南
本文標題:WCFWebAPI輕松實現(xiàn)REST
網(wǎng)站路徑:http://www.fisionsoft.com.cn/article/cococji.html


咨詢
建站咨詢
