RESTful Wcf是一種基于Http協(xié)議的服務(wù)架構(gòu)風(fēng)格。 相較 WCF、WebService 使用 SOAP、WSDL、WS-* 而言,幾乎所有的語言和網(wǎng)絡(luò)平臺(tái)都支持 HTTP 請求。
RESTful的幾點(diǎn)好處:
1、簡單的數(shù)據(jù)通訊方式,基于HTTP協(xié)議。避免了使用復(fù)雜的數(shù)據(jù)通訊方式。
2、避免了復(fù)雜的客戶端代理。
3、直接通過URI資源定向即可把服務(wù)暴露給調(diào)用者。
下面使用一個(gè)簡單的demo項(xiàng)目來看看啥是RESTful Wcf。
1、項(xiàng)目結(jié)構(gòu)【VS2010+.net 4.0】:
2、接口定義:定義了2個(gè)方法,分別代表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 /// 根據(jù)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、服務(wù)實(shí)現(xiàn)類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; //測試數(shù)據(jù) 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="段譽(yù)", Description="你爹真是風(fēng)流倜儻啊"} 25 new UserInfo(){ Id=3, Code="000002", Name="慕容復(fù)", 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資源請求和響應(yīng)格式:
1 /// <summary> 2 /// web請求格式 3 /// </summary> 4 public const WebMessageFormat WebRequestFormat = WebMessageFormat.Xml; 5 6 /// <summary> 7 /// web相應(yīng)格式 8 /// </summary> 9 public const WebMessageFormat WebResponseFormat = WebMessageFormat.Xml; 10 11 12 /// <summary> 13 /// 請求內(nèi)容封裝方式 14 /// </summary> 15 public const WebMessageBodyStyle WebBodyStyle = WebMessageBodyStyle.Bare;
5、Global全局資源文件,注冊服務(wù)的路由:
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 <!-- 為避免泄漏元數(shù)據(jù)信息,請?jiān)诓渴鹎皩⒁韵轮翟O(shè)置為 false 并刪除上面的元數(shù)據(jù)終結(jié)點(diǎn) --> 26 <serviceMetadata httpGetEnabled="true"/> 27 <!-- 要接收故障異常詳細(xì)信息以進(jìn)行調(diào)試,請將以下值設(shè)置為 true。在部署前設(shè)置為 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>
文件代碼都準(zhǔn)備的差不多了,運(yùn)行服務(wù)看下效果:
調(diào)用GET方法,返回xml數(shù)據(jù):
ok,一個(gè)RestFul WCF就搭建完畢。