RESTful Wcf是一種基於Http協議的服務架構風格, RESTful 的服務一般是架構層面上的考慮。 由於它天生就具備很好的跨平臺跨語言的集成能力,幾乎全部的語言和網絡平臺都支持 HTTP 請求,無需去實現複雜的客戶端代理,無需使用複雜的數據通信方式既能夠將咱們的服務暴露給任何須要的人,不管他使用 VB、Ruby、JavaScript,甚至是 HTML FORM,或者直接在瀏覽器地址欄輸入html
WCF 中經過 WebGetAttribute、WebInvokeAttribute (GET/PUT/POST/DELETE)、UriTemplate 定義 REST 的服務的調用方式, 經過 WebMessageFormat (Xml/Json) 定義消息傳遞的格式。web
RESTful的幾點好處(引用博文):ajax
一、簡單的數據通信方式,基於HTTP協議。避免了使用複雜的數據通信方式。json
二、避免了複雜的客戶端代理。跨域
三、直接經過URI資源定向便可把服務暴露給調用者。瀏覽器
下面就經過一個簡單的列子一步一步實現WCFRESTFulrestful
一、 新建以下項目網絡
二、 項目文件介紹架構
(1) IService1.cs 定義服務契約,在接口方法中定義RestFul請求規則。app
(2) Service1.svc 實現IService1.cs定義的服務契約。
(3) People.cs 數據契約,定義的實體對象
(4) Global.asax 全局資源文件中定義註冊路由
(5) Web.config 配置WCF服務。
三、 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
四、 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中的一個配置相關,咱們在下文中詳細介紹。
五、 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))); } } }
六、 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搭建成功,運行服務看效果。
一、 http://localhost:9315/Service1.svc(傳統的頁面,是否是很熟悉)
二、http://localhost:9315/user/help(RESTFul的風格,是否是眼前一亮
三、 經過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
文中有些的不對的地方歡迎你們指正。