您的位置:首页 > 其它

使用WCF 4.0 构建 REST Service

2010-12-03 16:56 330 查看

使用WCF 4.0 构建 REST Service

用过一段时间的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 {
// Edit the base address of Service1 by replacing the "Service1" string below
RouteTable.Routes.Add(new ServiceRoute("Service1", new WebServiceHostFactory(), typeof(Service1)));
}
}

通过代码我们可以看到,通过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" />
</modules>
</system.webServer>

<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
<standardEndpoints>
<webHttpEndpoint>
<!--
Configure the WCF REST service base address via the global.asax.cs file and the default endpoint
via the attributes on the <standardEndpoint> element below
-->
<standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"/>
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>
</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 {
return new List<SampleItem>() { new SampleItem() { Id = 1, StringValue = "Hello" } };
}

// POST /Service1/
[WebInvoke(UriTemplate = "", Method = "POST")]
public SampleItem Create(SampleItem instance)
{
throw new NotImplementedException();
}

// GET /Service1/100
[WebGet(UriTemplate = "{id}")]
public string Get(string id)
{
return "welcome";
}

// PUT /Service1/100
[WebInvoke(UriTemplate = "{id}", Method = "PUT")]
public SampleItem Update(string id, SampleItem instance)
{
throw new NotImplementedException();
}

// DELETE /Service1/100
[WebInvoke(UriTemplate = "{id}", Method = "DELETE")]
public void Delete(string id)
{
// TODO: Remove the instance of SampleItem with the given id from the collection
throw new NotImplementedException();
}
}

运行测试

为了测试,将Get(string id)进行修改。可以直接运行项目(F5)。

在地址栏中加上Service1,可以看到打开一个空白页面,此时内容已经生成,只是XML数默认不直接显示在页面上。





通过查看其Source,可以看到返回的数据集。





此时参数为空,也就是会调用下面一个返回集合的方法:

[WebGet(UriTemplate = "")]
public List<SampleItem> GetCollection()

同时,也可以发起带参数的GET请求,如/Service1/1/,则会调用相对应的参数函数:

[WebGet(UriTemplate = "{id}")]
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





在浏览器中打开可以看到结果。



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: