[转]使用WCF 4.0 构建 REST Service
本文转自:http://www.cnblogs.com/lanvige/archive/2010/12/03/set_up_rest_service_with_wcf_4.html
用过一段时间的Ruby on Rails,感觉它内置的RESTful结构非常的完美,也对.NET WCF 3实现REST颇有微议,今天在.NET 4.0下试了新的WCF 4,发现其重写了对REST的支持,使用了类似MVC Routing来配置URL导向,非常迷人。
下面来看下如何一步一步来创建新的REST结构的WCF项目。
创建项目
1 打开VS 2010,选择新建项目,我们选择已有的模板来方便创建新的项目,在左侧Online Templates中选择WCF REST Service Template 40(CS)。
![]()
接下来去安装这个模板到本地,第一次安装时需要同意该使用协议,点击“安装”:
![]()
这样我们就很简单的用这个模板生成了一个新的项目。
改变之处
该模板使用了一种新的结构来创建简单的REST Service,在细读代码前,先看下项目的文件结构:
![]()
相对于之前的版本
l 项目中不再有SVC文件,这样就不能每次都通过xx.svc/users/1 来访问,而是通过URL Routing来配置。
l 也不再有接口文件作契约。
Global.asax配置
可以看到在.NET 4中构建REST服务相当容易。项目通过在Global.asax中来配置类似于ASP.NET 中的Routing进行URL重定向。见如下代码。
1 public class Global : HttpApplication
2 {
3 void Application_Start(object sender, EventArgs e)
4 {
5 RegisterRoutes();
6 }
7
8 private void RegisterRoutes()
9 {
10 // Edit the base address of Service1 by replacing the "Service1" string below
11 RouteTable.Routes.Add(new ServiceRoute("Service1", new WebServiceHostFactory(), typeof(Service1)));
12 }
13 }
通过代码我们可以看到,通过ServiceRoute类来进行URL重定向的,这里我们配置了一个名为Service1的Resource,指定到Service1类上。
Web.config
同时,在web.config中包含着部署所需要的一些配置。下面的代码是默认生成的。
1 <?xml version="1.0"?>
2 <configuration>
3 <system.web>
4 <compilation debug="true" targetFramework="4.0" />
5 </system.web>
6
7 <system.webServer>
8 <modules runAllManagedModulesForAllRequests="true">
9 <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
10 </modules>
11 </system.webServer>
12
13 <system.serviceModel>
14 <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
15 <standardEndpoints>
16 <webHttpEndpoint>
17 <!--
18 Configure the WCF REST service base address via the global.asax.cs file and the default endpoint
19 via the attributes on the <standardEndpoint> element below
20 -->
21 <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"/>
22 </webHttpEndpoint>
23 </standardEndpoints>
24 </system.serviceModel>
25 </configuration>
Resource代码
默认生成的Resource:Service1代码,可以看到这是一个完整RESTful的结构,有着Get, Put, Post, Delete的完整支持。
1 [ServiceContract]
2 [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
3 [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
4 public class Service1
5 {
6 // GET /Service1/
7 [WebGet(UriTemplate = "")]
8 public List<SampleItem> GetCollection()
9 {
10 return new List<SampleItem>() { new SampleItem() { Id = 1, StringValue = "Hello" } };
11 }
12
13 // POST /Service1/
14 [WebInvoke(UriTemplate = "", Method = "POST")]
15 public SampleItem Create(SampleItem instance)
16 {
17 throw new NotImplementedException();
18 }
19
20 // GET /Service1/100
21 [WebGet(UriTemplate = "{id}")]
22 public string Get(string id)
23 {
24 return "welcome";
25 }
26
27 // PUT /Service1/100
28 [WebInvoke(UriTemplate = "{id}", Method = "PUT")]
29 public SampleItem Update(string id, SampleItem instance)
30 {
31 throw new NotImplementedException();
32 }
33
34 // DELETE /Service1/100
35 [WebInvoke(UriTemplate = "{id}", Method = "DELETE")]
36 public void Delete(string id)
37 {
38 // TODO: Remove the instance of SampleItem with the given id from the collection
39 throw new NotImplementedException();
40 }
41 }
运行测试
为了测试,将Get(string id)进行修改。可以直接运行项目(F5)。
在地址栏中加上Service1,可以看到打开一个空白页面,此时内容已经生成,只是XML数默认不直接显示在页面上。
![]()
通过查看其Source,可以看到返回的数据集。
![]()
此时参数为空,也就是会调用下面一个返回集合的方法:
1 [WebGet(UriTemplate = "")]
2 public List<SampleItem> GetCollection()
同时,也可以发起带参数的GET请求,如/Service1/1/,则会调用相对应的参数函数:
1 [WebGet(UriTemplate = "{id}")]
2 public string Get(string id)
Help 页面
模板同时也为我们生成了一个帮助页面,帮助我们快速了解该Resource所对应的URI祥情。
![]()
![]()
布署到IIS 7
该项目的布署和普通ASP.NET项目相同,这里写下方法。
将项目发布到本地磁盘:
![]()
在IIS中新建一个Site,在右侧Action下有一个Add Web Site。也可以在Default Web Site下新建一个Application,方式相同:
![]()
这一步一定要选Application pool为 ASP.NET v4.0,端口任意指定,这里使用8080
![]()
再强调一次,一定要选ASP.NET v4.0
![]()
在浏览器中打开可以看到结果。
![]()
[转]使用WCF 4.0 构建 REST Service的更多相关文章
- Service Discovery in WCF 4.0 – Part 1 z
Service Discovery in WCF 4.0 – Part 1 When designing a service oriented architecture (SOA) system, t ...
- Service Discovery in WCF 4.0 – Part 2 z
Service Discovery in WCF 4.0 – Part 2 In the previous post I discussed about the basic usage of WCF ...
- Java与WCF交互(二):WCF客户端调用Java web service【转】
原文:http://www.cnblogs.com/downmoon/archive/2010/08/25/1807982.html 在上篇< Java与WCF交互(一):Java客户端调用WC ...
- 转载——Java与WCF交互(二):WCF客户端调用Java Web Service
在上篇< Java与WCF交互(一):Java客户端调用WCF服务>中,我介绍了自己如何使用axis2生成java客户端的悲惨经历.有同学问起使用什么协议,经初步验证,发现只有wsHttp ...
- WCF 4.0 进阶系列 -- 随笔汇总
WCF4.0 进阶系列–前言 WCF4.0 进阶系列--第一章 WCF简介 WCF4.0进阶系列--第二章 寄宿WCF服务 WCF4.0进阶系列--第三章 构建健壮的程序和服务 WCF4.0进阶系列- ...
- 使用XFire+Spring构建Web Service(一)——helloWorld篇
转自:http://www.blogjava.net/amigoxie/archive/2007/09/26/148207.html原文出处:http://tech.it168.com/j/2007- ...
- 使用XFire+Spring构建Web Service
XFire是与Axis 2并列的新一代Web Service框架,通过提供简单的API支持Web Service各项标准协议,帮助你方便快速地开发Web Service应用. 相 对于Axis来说,目 ...
- XFire+Spring构建Web Service经验总结
使用工具 MyEclipse:6.5 ,tomcat6.x. 1.新建web项目,要导入用的包: 2程序结构: 3 web.xml配置文件 <?xml version="1.0&quo ...
- Android 开发 8.0版本启动Service的方法
前言 google在更新Android8.0后对Service的权限越发收紧.导致目前想要启动服务必需实现服务的前台化(否则在服务启动5秒后,系统将自动报错).下面我们就来看看如何在8.0上启动服务 ...
随机推荐
- 真实赛车3,FERRARI之魂不买FERRARI 599 GTO可以解锁顶点系列。
难点1,在仅有458 SPIDER的情况下,“TURBO BURST技巧混战”中 Mount Panorama速度快照,比较难.多重试十几次. 难点2,“TURBO BURST大满贯”中直道赛,用45 ...
- 租用游艇(简单区间dp)
租用游艇 时间限制: 1 Sec 内存限制: 128 MB提交: 1 解决: 1[提交][状态][讨论版][命题人:quanxing] 题目描述 长江游艇俱乐部在长江上设置了n 个游艇出租站1,2 ...
- Tensorflow笔记——神经网络图像识别(四)搭建模块化的神经网络八股(正则化,指数衰减学习率,滑动平均等优化)
实战案例: 数据X[x0,x1]为正太分布随机点, 标注Y_,当x0*x0+x1*x1<2时,y_=1(红),否则y_=0(蓝) 建立三个.py文件 1. generateds.py生成数据 ...
- Django ORM-02
6.ForeignKey 相关操作 1.正向查找 正向查找:那么什么是正向查找,我们知道对于一对多或者多对一的情况,我们一般将ForeignKey设置在多的一边,比如我们的书籍与出版社一般是多对一的, ...
- Git同时提交到多个远程仓库
使用git同时提交到多个远程库的操作方式为: 比如我需要你将同一份代码提交到如下的两个库中: https://gitee.com/FelixBinCloud/recruit.git https://g ...
- Oracle数据库备份与恢复的三种方法
转自blueskys567原文Oracle数据库备份与恢复的三种方法, 2006-10. 有删改 Oracle数据库有三种标准的备份方法,它们分别是导出/导入(EXP/IMP).热备份和冷备份. 导出 ...
- RAD XE8
http://community.embarcadero.com/index.php/blogs/entry/rad-studio-2015-roadmap http://www.embarcader ...
- FORALL用法小结
本文主要翻译.整理了ORACLE官方文档上有关FORALL的部份内容,不妥之处,还希望多和大家交流. 在发送语句到SQL引擎前,FORALL语句告知PL/SQL 引擎批挷定输入集合.尽管FORALL语 ...
- jQuery deferred.resolve() 方法
jQuery deferred.resolve() 方法 deferred.resolve() 函数用于解决Deferred(延迟)对象,并根据给定的args参数调用任何 doneCallbacks ...
- js字符转换为数字
转换函数.强制类型转换.利用js变量弱类型转换. 1. 转换函数: js提供了parseInt()和parseFloat()两个转换函数.前者把值转换成整数,后者把值转换成浮点数.只有对String类 ...