Announcement: WCF Web API is now ASP.NET Web API! ASP.NET Web API released with ASP.NET MVC 4 Beta. The WCF Web API and WCF Support for jQuery content on this site will be removed by the end of 2012. 先体验一下,如果没有 WCF Web API,直接用 WCF 实现 REST 有多麻烦: 1. 创建 WCF 服务(ServiceContract)。 2. 创建 .svc 文件指向该 WCF 服务。 3. 在 web.config 中添加 <service>/<endpoint> 配置,并将 binding 设置为 webHttpBinding,示例配置如下: <services> 4. 在 web.config 中添加 <endpointBehaviors>/<behavior> 配置,并在其中添加<webHttp />,在第3步的配置中添加该behaviorConfiguration(比如上面代码中的behaviorConfiguration="RESTFul"),示例配置如下: <endpointBehaviors> 5. 在 OperationContract 方法上增加 WebInvoke 属性,示例代码如下: [OperationContract] 上面的5步已经够麻烦了。开始以为到此就可以收工了,哪知不运行不知道,一运行吓一跳: Operation 'GetRecentNews' in contract 'INewsRestService' has a path variable named 'itemcount' which does not 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./wikipage?title=WCF%20HTTP) 1. 在提供 REST 服务的方法上增加 [WebGet(UriTemplate = "")] 属性,示例代码如下: [ServiceContract] 2. 在 Global.asax 的 Application_Start 中添加路由,示例代码如下: protected void Application_Start(object sender, EventArgs e) 注:需要通过 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>)。 相关内容 英文: Getting Started: Building a simple Web API 中文: |
|