上一篇,我們介紹了如何使用JS去調用WCF。但實際開發中,各大網站的API都是REST風格,那我們也REST下,順便用JS調用。
廢話不多說,我就把幾個比較重要的代碼貼下:
接口:
using System.ServiceModel; using System.ServiceModel.Web; [ServiceContract] public interface IproductService { [WebGet(UriTemplate = "all", ResponseFormat = WebMessageFormat.Json)] //不設置這個 默認就是xml IEnumerable<Product> GetAll(); [WebGet(UriTemplate="{id}")] Product Get(string id); [WebInvoke(UriTemplate="/",Method="POST")] void Create(Product product); [WebInvoke(UriTemplate = "/", Method = "PUT")] void Update(Product product); [WebInvoke(UriTemplate="/",Method="Delete")] void Detele(string id); }
服務:
using System.ServiceModel.Activation;//這個告訴我們是否動態加載ServiceHost宿主 using System.ServiceModel; //要以IIS管道運行WCF服務 只需要加上這個特性就可以 運行網站的同時 運行WCF服務 AJAX也可以請求到了 [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)] //對象在每次調用前創建,在調用后回收 public class ProductService:IproductService { public static IList<Product> products = new List<Product>() { new Product{Id="1",Department="IT部門",Name="Yuhao",Grade="軟件開發"}, new Product{Id="2",Department="IT部門",Name="Yuhao1",Grade="前端開發"} }; #region IproductService 成員 public IEnumerable<Product> GetAll() { return products; } public Product Get(string id) { Product product = products.FirstOrDefault(p => p.Id == id); if (null != product) { return product; } return null; } public void Create(Product product) { products.Add(product); } public void Update(Product product) { Product p = this.Get(product.Id); if (null != p) { products.Remove(p); } products.Add(product); } public void Detele(string id) { Product product = this.Get(id); if (null != product) { products.Remove(product); } } #endregion }
webconfig:
<system.webServer> <modules runAllManagedModulesForAllRequests="true"> <!--這里注冊路由 直接拷貝過去就好 不需要wcf rest 模板 --> <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" /> </modules> </system.webServer> <system.serviceModel> <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/> <!--以asp.net 管道運行wcf rest 並且允許綁定到多個IIS上--> <standardEndpoints> <webHttpEndpoint> <!--編寫REST的時候使用的配置--> <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"/> <!--helpEnabled 是否開啟幫助 automaticFormatSelectionEnabled 是否啟動自動格式--> </webHttpEndpoint> </standardEndpoints> </system.serviceModel>
注冊路由:
void Application_Start(object sender, EventArgs e) { RegisterRoutes(); //注冊路由 } private void RegisterRoutes() { //把WCF rest 綁定到路由上 System.Web.Routing.RouteTable.Routes.Add(new System.ServiceModel.Activation.ServiceRoute("ProductService", new System.ServiceModel.Activation.WebServiceHostFactory(), typeof(ProductService))); }
好了,到此為主,是不是很簡單,但這里是用的路由來幫助完成,所以下一篇,我就要說了現在流行的web api來做。
其實,我寫這么多WCF服務,主要是告訴你 web api 是有多么簡單,多好用,沒有那么大配置和繁瑣的地方。
示例代碼下載:WcfDemo(.net4.0)Rest.JS.zip