构建RESTful风格的WCF服务

RESTful Wcf是一种基于Http协议的服务架构风格。 相较 WCF、WebService 使用 SOAP、WSDL、WS-* 而言,几乎所有的语言和网络平台都支持 HTTP 请求。

RESTful的几点好处:

1、简单的数据通讯方式,基于HTTP协议。避免了使用复杂的数据通讯方式。

2、避免了复杂的客户端代理。

3、直接通过URI资源定向即可把服务暴露给调用者。

下面使用一个简单的demo项目来看看啥是RESTful Wcf。

1、项目结构【VS2010+.net 4.0】:

构建RESTful风格的WCF服务_第1张图片

2、接口定义:定义了2个方法,分别代表GET、POST典型请求方式。

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.ServiceModel;
 6 using System.ServiceModel.Web;
 7 using MyWcfService.Model;
 8 namespace MyWcfService
 9 {
10     [ServiceContract(Namespace = ServiceEnvironment.ServiceNamespace, Name = "user")]
11     public interface IUserService
12     {
13         /// <summary>
14         /// 根据code获取对象(GET请求处理)
15         /// </summary>
16         /// <param name="code"></param>
17         /// <returns></returns>
18         [OperationContract]
19         [WebGet(UriTemplate = "search/{code}", ResponseFormat = ServiceEnvironment.WebResponseFormat, RequestFormat = ServiceEnvironment.WebRequestFormat, BodyStyle = ServiceEnvironment.WebBodyStyle)]
20         UserInfo GetUserInfoSingle(string code);
21 
22         /// <summary>
23         /// 注册新的用户(POST请求处理)
24         /// </summary>
25         /// <param name="user">注册用户信息</param>
26         /// <returns>注册成功返回注册用户基本信息</returns>
27         [OperationContract]
28         [WebInvoke(Method = "POST", UriTemplate = "register", ResponseFormat = ServiceEnvironment.WebResponseFormat, RequestFormat = ServiceEnvironment.WebRequestFormat, BodyStyle = ServiceEnvironment.WebBodyStyle)]
29         UserInfo Register(UserInfo user);
30     }
31 }

3、服务实现类WcfUserService:

 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 using MyWcfService.Model;
 9 using System.ServiceModel.Activation;
10 
11 namespace MyWcfService
12 {
13     [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
14     public class WcfUserService : IUserService
15     {
18         public UserInfo GetUserInfoSingle(string code)
19         {
20             // var request= WebOperationContext.Current.IncomingRequest;
         //测试数据
21 IList<UserInfo> list = new List<UserInfo>() 22 { 23 new UserInfo(){ Id=1, Code="000001", Name="乔峰", Description="乔大爷啊"}, 24 new UserInfo(){ Id=2, Code="600000", Name="段誉", Description="你爹真是风流倜傥啊"} 25 new UserInfo(){ Id=3, Code="000002", Name="慕容复", Description="妹子被楼上的抢咯,太失败了"}, 26 new UserInfo(){ Id=4, Code="000008", Name="庄聚贤", Description="无所事事的帅哥庄聚贤"} 27 }; 28 return list.Where(e => e.Code == code).FirstOrDefault(); 29 }
32 public UserInfo Register(UserInfo user) 33 { 34 if (user == null) 35 return null; 36 user.Description = "POST搞定了!"; 37 return user; 38 } 40 } 41 }

4、定义web资源请求和响应格式:

 1 /// <summary>
 2         /// web请求格式
 3         /// </summary>
 4         public const WebMessageFormat WebRequestFormat = WebMessageFormat.Xml;
 5 
 6         /// <summary>
 7         /// web相应格式
 8         /// </summary>
 9         public const WebMessageFormat WebResponseFormat = WebMessageFormat.Xml;
10 
11 
12         /// <summary>
13         /// 请求内容封装方式
14         /// </summary>
15         public const WebMessageBodyStyle WebBodyStyle = WebMessageBodyStyle.Bare;

5、Global全局资源文件,注册服务的路由:

 1         protected void Application_Start(object sender, EventArgs e)
 2         {
 3             RegisterRoutes();
 4         }
 5 
 6         private static void RegisterRoutes()
 7         {
 8             RouteTable.Routes.Add(new ServiceRoute("user", new WebServiceHostFactory(), GetServiceType("WcfUserService")));
 9         }
10 
11         private static Type GetServiceType(string typeName)
12         {
13             string typeFullName = String.Format("MyWcfService.{0},MyWcfService", typeName);
14             return Type.GetType(typeFullName);
15         }

6、wcf配置文件:

 1  <system.serviceModel>
 2     <bindings>
 3       <netTcpBinding>
 4         <binding name="defaultNetTcpBinding" closeTimeout="00:01:00"
 5             openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
 6             transactionFlow="false" transferMode="Buffered" transactionProtocol="OleTransactions"
 7             hostNameComparisonMode="StrongWildcard" listenBacklog="10"
 8             maxBufferPoolSize="2147483647" maxBufferSize="2147483647" maxConnections="100"
 9             maxReceivedMessageSize="2147483647">
10           <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
11               maxBytesPerRead="4096" maxNameTableCharCount="16384" />
12           <reliableSession ordered="true" inactivityTimeout="00:10:00"
13               enabled="false" />
14           <security mode="None">
15             <transport clientCredentialType="Windows" protectionLevel="EncryptAndSign" />
16             <message clientCredentialType="Windows" />
17           </security>
18         </binding>
19       </netTcpBinding>
20     </bindings>
21     <behaviors>
22       <serviceBehaviors>
23 
24         <behavior name="defaultResultBehavior">
25           <!-- 为避免泄漏元数据信息,请在部署前将以下值设置为 false 并删除上面的元数据终结点 -->
26           <serviceMetadata httpGetEnabled="true"/>
27           <!-- 要接收故障异常详细信息以进行调试,请将以下值设置为 true。在部署前设置为 false 以避免泄漏异常信息 -->
28           <serviceDebug includeExceptionDetailInFaults="true"/>
29           <dataContractSerializer maxItemsInObjectGraph="6553500"/>
30         </behavior>
31       </serviceBehaviors>
32       <endpointBehaviors>
33         <behavior name="defaultRestEndpointBehavior">
34           <webHttp helpEnabled="true" automaticFormatSelectionEnabled="true" />
35           <dataContractSerializer maxItemsInObjectGraph="6553500"/>
36         </behavior>
37         <behavior>
38           <dataContractSerializer maxItemsInObjectGraph="6553500"/>
39         </behavior>
40       </endpointBehaviors>
41     </behaviors>
42     <services>
43       <service name="MyWcfService.WcfUserService" behaviorConfiguration="defaultResultBehavior">
44         <endpoint contract="MyWcfService.IUserService" binding="webHttpBinding" behaviorConfiguration="defaultRestEndpointBehavior" />
45       </service>
46       
47     </services>
48     <serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" />
49   </system.serviceModel>

文件代码都准备的差不多了,运行服务看下效果:

调用GET方法,返回xml数据:

ok,一个RestFul WCF就搭建完毕。

下一篇文章还是基于这个demo,如何使用dynamic解析Http RestFul xml格式响应数据,并展现在客户端。


你可能感兴趣的:(构建RESTful风格的WCF服务)