Rest 它是用于创建分布式超文本媒体的一种架构方式,我们可以通过标准的HTTP(GET,POST,PUT,DELETE)操作来构建基于面向资源的软件架构方式(Resource-Oriented Architecture (ROA))。它是独立于任何技术或者平台的,所以人们经常将符合这种操作规范的服务称为“RESTful services”。因为WCF能够构建符合这种规范的服务,所以我们经常称之为 WCF Restful Services。

由于传统的WCF Service可以使用tcp,net.msmq,http等协议进行数据交换,并且采用了RPC(Remote Procedure Call)的工作方式,客户端需要添加对服务端的引用才能完成。但是WCF Restful Service完全使用Http协议来进行,并且无需添加客户端引用,所以方便很多。

 WebInvoke

其中,Method 方法主要是表明可以接受客户端的请求类型,这里有四种:GET,POST,PUT,DELETE,其中GET为请求数据,POST为更新数据,PUT为新增数据,DELETE代表着删除数据。

然后ResponseFormat 则代表着返回的数据组织,如果是Json则表明客户端会接收到Json数据,如果是XML则表明客户端会接收到XML组织的数据。BodyStyle 代表返回数据的包装对象,如果是Bare则表明数据无任何包装,原生数据返回;如果是Wrapped则表明数据会在最外层包装一个当前函数名称加上Result的套。比如对于Delete对象,则会返回 DeleteResult:{******},会造成DataContractJsonSerializer无法进行反序列化。

UriTemplate 主要用于指定操作的URI路径,只要用户输入了合法路径并采用了正确的请求方式,就会触发该函数。

最后说到的就是URI后面跟的参数的问题,由于函数只能接受string类型的,所以如果传入参数是string类型,则可以使用UriTemplate = "{bookID}"的路径,反之,则需要加上/?param1={paramname}的方式

 

服务端

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Runtime.Serialization;
 5 using System.ServiceModel;
 6 using System.ServiceModel.Web;
 7 using System.Text;
 8 
 9 namespace IISWCF
10 {
11     // 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码和配置文件中的接口名“IService1”。
12     [ServiceContract]
13     public interface IService1
14     {
15 
16         #region TEST
17 
18         [OperationContract(Name = "TestPost")]
19         [WebInvoke(Method = "POST", UriTemplate = "TestPost/{str}", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
20         UserInfo TestPost(string str);
21 
22         [OperationContract, WebInvoke(Method = "GET", UriTemplate = "TestGet1")]
23         string TestGet1();
24 
25         [OperationContract(Name = "TestGet2")]
26         [WebGet(UriTemplate = "TestGet2/{Code}/{Card}",
27             BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Xml)]
28         UserInfo TestGet2(string Code, string Card);
29 
30         #endregion
31     }
32 
33 
34     // 使用下面示例中说明的数据约定将复合类型添加到服务操作。
35     [DataContract]
36     public class UserInfo
37     {
38          [DataMember]
39         public string Name { get; set; }
40          [DataMember]
41         public string Code { get; set; }
42          [DataMember]
43         public string Card { get; set; }
44     }
45 }
服务契约

相关文章: