RESTful Wcf是一種基於Http協議的服務架構風格, RESTful 的服務通常是架構層面上的考慮。 因為它天生就具有很好的跨平台跨語言的集成能力,幾乎所有的語言和網絡平台都支持 HTTP 請求,無需去實現復雜的客戶端代理,無需使用復雜的數據通訊方式既可以將我們的服務暴露給任何需要的人,無論他使用 VB、Ruby、JavaScript,甚至是 HTML FORM,或者直接在瀏覽器地址欄輸入
WCF 中通過 WebGetAttribute、WebInvokeAttribute (GET/PUT/POST/DELETE)、UriTemplate 定義 REST 的服務的調用方式, 通過 WebMessageFormat (Xml/Json) 定義消息傳遞的格式。
RESTful的幾點好處(引用博文):
1、簡單的數據通訊方式,基於HTTP協議。避免了使用復雜的數據通訊方式。
2、避免了復雜的客戶端代理。
3、直接通過URI資源定向即可把服務暴露給調用者。
下面就通過一個簡單的列子一步一步實現WCFRESTFul
1、 新建如下項目
2、 項目文件介紹
(1) IService1.cs 定義服務契約,在接口方法中定義RestFul請求規則。
(2) Service1.svc 實現IService1.cs定義的服務契約。
(3) People.cs 數據契約,定義的實體對象
(4) Global.asax 全局資源文件中定義注冊路由
(5) Web.config 配置WCF服務。
3、 IService1.cs接口定義三個方法,包含GET和POST請求
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Web; using System.Text; namespace WcfRestFulService { // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together. [ServiceContract(Name="user")] public interface IService1 { [OperationContract] [WebInvoke(UriTemplate = "get/{value}", Method = "GET", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)] string GetData(string value); [OperationContract] [WebInvoke(UriTemplate = "add", Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)] string addPeople(People p); [OperationContract] [WebInvoke(UriTemplate = "GetList/{value}", Method = "GET", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)] List<People> GetList(string value); } }
注意:通過WebInvoke屬性的Method值說明該請求的類型,UriTemplate值說明url路由。接口中[ServiceContract(Name="user")]的定義,我們的URL路徑中將會用到user
4、 Service1.svc實現契約
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Web; using System.Text; using System.ServiceModel.Activation; namespace WcfRestFulService { // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together. [AspNetCompatibilityRequirements( RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class Service1 : IService1 { public string GetData(string value) { return string.Format("You entered: {0}", value); } public string addPeople(People p) { if (p == null) { return "People is Null"; } return p.Name; } public List<People> GetList(string value) { return new List<People> { new People(){Id=1,Name="eric"}}; } } }
注意:[AspNetCompatibilityRequirements( RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]的定義跟我們在webconfig中的一個配置相關,我們在下文中詳細介紹。
5、 Global全局資源文件,注冊服務的路由:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Security; using System.Web.SessionState; using System.Web.Routing; using System.ServiceModel.Activation; namespace WcfRestFulService { public class Global : System.Web.HttpApplication { protected void Application_Start(object sender, EventArgs e) { RegistrRoutes(); } private void RegistrRoutes() { //說明:ServiceRoute需要引用 System.ServiceModel.Activation.dll RouteTable.Routes.Add(new ServiceRoute("user", new WebServiceHostFactory(), typeof(Service1))); } } }
6、 Web.config配置文件
<?xml version="1.0"?> <configuration> <system.web> <compilation debug="true" targetFramework="4.0" /> </system.web> <system.serviceModel> <behaviors> <serviceBehaviors> <behavior name="defaultResultBehavior"> <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment --> <serviceMetadata httpGetEnabled="true"/> <!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information --> <serviceDebug includeExceptionDetailInFaults="false"/> <dataContractSerializer maxItemsInObjectGraph="6553500"/> </behavior> </serviceBehaviors> <endpointBehaviors> <behavior name="defaultRestEndpointBehavior"> <webHttp helpEnabled="true" automaticFormatSelectionEnabled="true" /> <dataContractSerializer maxItemsInObjectGraph="6553500"/> </behavior> </endpointBehaviors> </behaviors> <services> <service name="WcfRestFulService.Service1" behaviorConfiguration="defaultResultBehavior"> <endpoint binding="webHttpBinding" contract="WcfRestFulService.IService1" behaviorConfiguration="defaultRestEndpointBehavior"></endpoint> </service> </services> <serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" /> </system.serviceModel> <system.webServer> <modules runAllManagedModulesForAllRequests="true"/> </system.webServer> </configuration>
說明:在配置文件中我們看<serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" />節點,如果使aspNetCompatibilityEnabled="true"必須在Service1.svc聲明[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)],其中RequirementsMode的值也可以為AspNetCompatibilityRequirementsMode. Required
至此我們的WCFRESFul搭建成功,運行服務看效果。
1、 http://localhost:9315/Service1.svc(傳統的頁面,是不是很熟悉)
2、http://localhost:9315/user/help(RESTFul的風格,是不是眼前一亮
3、 通過RESTFul風格調用服務
(1)、http://localhost:9315/user/get/1調用服務string GetData(string value),參數值為1
(2)、http://localhost:9315/user/add 調用string addPeople(People p)服務
下面我們開始創建一個簡答的ajax調用列子測試一下WC FRESTFul服務
注意:如果你是用VS自帶的IIS調試,WCF RESTFul生成的URL與調用WCF服務的URL端口號要保持一致,要不然用ajax調用瀏覽器會認為跨域。 比如:http://localhost:9315/user/get/1 和 http://localhost:9315/Default.aspx,
我是采用win7系統的IIS 7調試的。
服務地址配置為:http://localhost/wfcrestful/user/help
調用服務的Web頁面的地址為:http://localhost/restfulTest/WebForm1.aspx
調用服務string GetData(string value)
$.get("http://localhost/wfcrestful/user/get/1", function (json) { alert(json) });
調用服務:string addPeople(People p)
$.ajax({ "url": "http://localhost/wfcrestful/user/add", "type": "POST", "contentType": "application/json", "dataType": "json", "data": '{\"Id\":1,\"Name\":\"我是輸入的內容\"}', "success": function (returnValue) { alert(returnValue); } });
調用服務GetList(string value)
$.get("http://localhost/wfcrestful/user/GetList/22", function (json) { alert(json[0].Name); })
至此整個DEMO已經完成,請點擊下載源碼。
PS:WCF RESTFul已經是過時的技術了,有興趣的童鞋們可以研究一下 MVC WebApi
文中有些的不對的地方歡迎大家指正。