REST(Representational State Transfer)是 RoyFielding 提出的一个描述互联系统架构风格的名词。为什么称为REST?Web本质上由各种各样的资源组成,资源由URI 唯一标识。浏览器(或者任何其它类似于浏览器的应用程序)将展示出该资源的一种表现方式,或者一种表现状态。如果用户在该页面中定向到指向其它资源的链接,则将访问该资源,并表现出它的状态。这意味着客户端应用程序随着每个资源表现状态的不同而发生状态转移,也即所谓REST。
典型的基于 SOAP 的 Web 服务以操作为中心,每个操作接受XML 文档作为输入,提供XML 文档作为输出。在本质上讲,它们是RPC 风格的。而在遵循REST 原则的ROA 应用中,服务是以资源为中心的,对每个资源的操作都是标准化的HTTP 方法。
闲话少说,我们来看看如何用C#实现一个Rest 风格的web服务:
·定义service 的契约
·定义URL Routing
·实现 service
·为服务编写宿主程序
定义service 的契约
使用VS2010创建一个新的类库工程,命名为RESTServiceLib,为该工程添加引用System.ServiceModel 和System.ServiceModel.Web。创建一个CS文命名为IRESTDemoServices.CS,并定义如下接口:
public interface IRESTDemoServices { stringGetClientNameById(string Id); }为了让.NetFrameWork识别这是一个service 接口,我们给接口加上ServiceContract特性,给方法加上OperationContract特性:
[ServiceContract(Name = "RESTDemoServices")] public interface IRESTDemoServices { [OperationContract] string GetClientNameById(int Id); }当然我们可以在这个service接口中定义更多的方法,这里是举个简单的例子,就不加其他方法了。
定义URL Routing
新建一个Routing类
public static class Routing { public const string GetClientRoute = "/Client/{id}"; }将Routing与service接口中的方法关联上,注意Routing与service中的参数名称id必须一致(不区分大小写)
[ServiceContract(Name = "RESTDemoServices")] public interface IRESTDemoServices { [OperationContract] [WebGet(UriTemplate = Routing.GetClientRoute, BodyStyle = WebMessageBodyStyle.Bare)] string GetClientNameById(string Id); }WebGet特性指定GetClientNameById可以被特定的Url以GET方法访问。
实现Service
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Single, IncludeExceptionDetailInFaults = true)] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class RestDemoServices:IRESTDemoServices { public string GetClientNameById(string Id) { Random r = new Random(); string ReturnString=""; int Idnum=Convert.ToInt32(id); for (int i = 0; i < Idnum; i++) ReturnString += char.ConvertFromUtf32(r.Next(65, 85)); return ReturnString; } }这个方法(GetClientNameById)的实现仅仅是根据id 返回一个长度为id的随机字符串,在实际的项目中更可能是访问数据库得到想要的信息然后返回。
为服务编写宿主程序
使用VS2010创建一个新的Console Application 项目,在项目的属性中将TargetFramework该为.NET Framework 4, 默认是.NET Framework4 client profile,因为.NET Framework4 client profile一般不支持服务器端的辅助类。为项目添加引用System.ServiceModel.Web,并将RESTServiceLib工程添加为引用,其代码实现如下:
static void Main(string[] args) { RestDemoServices DemoServices = new RestDemoServices(); WebServiceHost _serviceHost = new WebServiceHost(DemoServices, new Uri("http://localhost:8000/DEMOService")); _serviceHost.Open(); Console.ReadKey(); _serviceHost.Close(); }以上代码为RestDemoServices提供宿主环境,并将其地址指定为http://localhost:8000/DEMOService ,运行该程序,打开IE输入http://localhost:8000/DEMOService/Client/22
若需要使用IIS作为宿主则需要新建一个svc文件,内容如下:
<%@ ServiceHost Language="C#" Debug="true" Service="RESTService.Lib.RestDemoServices" Factory="System.ServiceModel.Activation.WebServiceHostFactory"%>