1、啥是RESTFul 服務 在我們創建簡單小程式前,先來學習下RESTFul 服務。RESTFul服務就是遵循了 Representational State Transfer(可以參考http://blog.csdn.net/zhruifei/article/details/50633495) ...
1、啥是RESTFul 服務
在我們創建簡單小程式前,先來學習下RESTFul 服務。RESTFul服務就是遵循了 Representational State Transfer(可以參考http://blog.csdn.net/zhruifei/article/details/50633495) 這個架構的一種架構。WCF允許我們使用SOAP 通過各種協議,協議包括,HTTP,TCP,MSMQ,Named Pipes等進行交換信息。現在我們通過一個最常用的協議HTTP協議來講述WCF服務,REST服務通過HTTP來進行最常用的CRUD(Read(GET)/Create(POST)/Update(PUT)/Delete(DELETE))功能,在這裡我們先實現一個簡單的GET功能
2、創建restful 服務
下麵是5步創建你的rest服務並且返回xml格式
- 創建WCF Service Project.
- 準備數據
- 創建Service Contract
- 繼承Service
- 配置服務和行為
1)打開vs-新建項目-選擇WCF服務應用程式
2,新建一個類 car.cs
[DataContract] public class Car { [DataMember] public string color { get; set; } [DataMember] public double speed { get; set; } [DataMember] public double price { get; set; } } public partial class Cars { public static readonly Cars _instance = new Cars(); private Cars() { } public static Cars Instance { get { return _instance; } } public List<Car> CarList { get { return carLists; } } private List<Car> carLists = new List<Car> { new Car { color = "red", speed = 200, price = 200 }, new Car{color = "blue", speed = 200, price = 200}, new Car{color="green",speed=300,price=400} }; }
3)新建WCF 服務--如下圖所示
系統將新疆兩個文件,包括ICarRestService.cs 介面文件如下圖所示:
下麵我們將Dowork 方法改為GetCarList 方法
如下所示:
- Method="Get" 代表這Http獲取數據的方式
- RequestFormat = WebMessageFormat.Json 請求的數據是JSON格式,當然RequestFormat = WebMessageFormat.Xml 請求的是XML格式
- UriTemplate = "GetCarList/" 請求了URL
5)配置服務和行為
<?xml version="1.0"?> <configuration> <appSettings> <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" /> </appSettings> <system.web> <compilation debug="true" targetFramework="4.5" /> <httpRuntime targetFramework="4.5"/> </system.web> <system.serviceModel> <services> <service name="MyRESTService.ProductRESTService" behaviorConfiguration="serviceBehavior"> <endpoint address="" binding="webHttpBinding" contract="MyRESTService.IProductRESTService" behaviorConfiguration="web"></endpoint> </service> </services> <behaviors> <serviceBehaviors> <behavior name="serviceBehavior"> <serviceMetadata httpGetEnabled="true"/> <serviceDebug includeExceptionDetailInFaults="false"/> </behavior> </serviceBehaviors> <endpointBehaviors> <behavior name="web"> <webHttp/> </behavior> </endpointBehaviors> </behaviors> <protocolMapping> <add binding="basicHttpsBinding" scheme="https" /> </protocolMapping> <serviceHostingEnvironment multipleSiteBindingsEnabled="true" /> </system.serviceModel> <system.webServer> <modules runAllManagedModulesForAllRequests="true"/> <!-- To browse web app root directory during debugging, set the value below to true. Set to false before deployment to avoid disclosing web app folder information. --> <directoryBrowse enabled="true"/> </system.webServer> </configuration>
配置自己寫寫就明白了 此處的webHTTPBinding 是rest 服務專用的綁定模式
6)然後在瀏覽器中輸入:http://localhost:30547/CarsRestService.svc/GetCarList/
得到的結果如下:
哈哈這樣第一個rest 服務就好了,希望可以幫助到你