在上一篇(WCF學習之旅—實現REST服務(二十二))文章中簡單介紹了一下RestFul與WCF支持RestFul所提供的方法,本文講解一下如何創建一個支持REST的WCF服務端程式。 四、在WCF中創建REST服務 1. 在SCF.Contracts 在創建一個服務契約IBookRestServi ...
在上一篇(WCF學習之旅—實現REST服務(二十二))文章中簡單介紹了一下RestFul與WCF支持RestFul所提供的方法,本文講解一下如何創建一個支持REST的WCF服務端程式。
四、在WCF中創建REST服務
1. 在SCF.Contracts 在創建一個服務契約IBookRestService.
這裡提供兩個方法,分別採用GET和POST方式訪問。
我們可以看到,與普通WCF服務契約不同的是,需要額外用WebGet或者WebInvoke指定REST訪問的方式。另外還要指定消息包裝樣式和消息格式,預設的消息請求和響應格式為XML,若選擇JSON需要顯式聲明。
UriTemplate用來將方法映射到具體的Uri上,但如果不指定映射,將映射到預設的Uri。比如採用Get訪問的GetBook方法,預設映射是:/ GetBook?BookId={BookId}。
在編寫代碼的過程中,會出現如下圖中1的錯誤,請引用下圖2處的
using SCF.Model; using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel; using System.ServiceModel.Web; using System.Text; using System.Threading.Tasks; namespace SCF.Contracts { [DataContractFormat] [ServiceContract] public interface IBookRestService { //[WebGet(UriTemplate = "/Books/Get/{BookId}/{categroy}", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)] [WebGet(UriTemplate = "/Books/Get/{BookId}", BodyStyle = WebMessageBodyStyle.Bare)] [OperationContract] List<Books> GetBook(string BookId); //[WebInvoke(Method = "POST", UriTemplate = "/Books/Create", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] [WebInvoke(Method = "POST", UriTemplate = "/Books/Add", BodyStyle = WebMessageBodyStyle.Bare)] [OperationContract] Result AddBook(Books book); } }
2. 在項目SCF.Model中創建一個實體對象Books與一個返回對象Result,用作數據傳輸的載體,下麵是Books.cs的內容
namespace SCF.Model { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; using System.Runtime.Serialization; ///DataContract 數據契約:服務端和客戶端之間要傳送的自定義數據類型 [DataContract(Namespace = "http://tempuri.org/")] public partial class Books { /// <summary> /// 在數據傳送過程中,只有成員變數可以被傳送而成員方法不可以。 /// 並且只有當成員變數加上DataMember時才可以被序列進行數據傳輸, /// 如果不加DataMember,客戶端將無法獲得該屬性的任何信息 /// </summary> [DataMember] [Key] public int BookID { get; set; } [DataMember] [Required] public string Category { get; set; } [DataMember] [Required] public string Name { get; set; } [DataMember] public int Numberofcopies { get; set; } [DataMember] public int AuthorID { get; set; } [DataMember] public decimal Price { get; set; } [DataMember] public DateTime PublishDate { get; set; } [StringLength(5)] [DataMember] public string Rating { get; set; } } } using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace SCF.Model { [DataContract(Namespace = "http://tempuri.org/")] public class Result { [DataMember] public string Message { get; set; } } }
3. 在SCF.WcfService項目中實現在SCF.Contracts項目中定義的服務契約。這裡最簡單的實現GetBook和AddBook兩個方法的邏輯。
using SCF.Contracts; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; using SCF.Model; using SCF.Common; namespace SCF.WcfService { // 註意: 使用“重構”菜單上的“重命名”命令,可以同時更改代碼、svc 和配置文件中的類名“BookRestService”。 // 註意: 為了啟動 WCF 測試客戶端以測試此服務,請在解決方案資源管理器中選擇 BookRestService.svc 或 BookRestService.svc.cs,然後開始調試。 public class BookRestService : IBookRestService { Entities db = new Entities(); public Result AddBook(Books book) { Result result = new Result(); try { db.Books.Add(book); db.SaveChanges(); result.Message = string.Format("書名:{0} 已經添加!",book.Name); } catch (Exception ex) { result.Message =ex.Message; } return result; } public List<Books> GetBook(string BookId) { var cateLst = new List<string>(); var cateQry = from d in db.Books orderby d.Category select d.Category; cateLst.AddRange(cateQry.Distinct()); var books = from m in db.Books select m; if (!String.IsNullOrEmpty(BookId)) { books = books.Where(s => s.Name.Contains(BookId)); } List<Books> list = null; list = books.ToList<Books>(); return list; } } }
4. 在配置文件在中配置我們的Rest服務,必須使用WebHttpBehavior對服務的終結點進行配置。
<?xml version="1.0" encoding="utf-8"?> <configuration> <configSections> <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --> <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework,
Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> </configSections> <entityFramework> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" /> <providers> <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /> </providers> </entityFramework> <system.serviceModel> <bindings> <webHttpBinding> <binding name="RestWebBinding"> </binding> </webHttpBinding> </bindings> <behaviors> <serviceBehaviors> <behavior name="metadataBehavior"> <serviceMetadata httpGetEnabled="true" httpGetUrl="http://127.0.0.1:8888/BookService/metadata" /> <serviceDebug includeExceptionDetailInFaults="True" /> </behavior> <behavior name="RestServiceBehavior"> </behavior> </serviceBehaviors> <endpointBehaviors> <behavior name="RestWebBehavior"> <!--這裡必須設置--> <webHttp /> </behavior> </endpointBehaviors> </behaviors> <services> <service behaviorConfiguration="metadataBehavior" name="SCF.WcfService.BookService"> <endpoint address="http://127.0.0.1:8888/BookService" binding="wsHttpBinding" contract="SCF.Contracts.IBookService" /> </service> <service name="SCF.WcfService.BookRestService" behaviorConfiguration="RestServiceBehavior"> <endpoint address="http://127.0.0.1:8888/" behaviorConfiguration="RestWebBehavior" binding="webHttpBinding" bindingConfiguration="RestWebBinding" contract="SCF.Contracts.IBookRestService"> </endpoint> </service> </services> </system.serviceModel> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" /> </startup> <connectionStrings> <add name="Entities" connectionString="metadata=res://*/BookModel.csdl|res://*/BookModel.ssdl|res://*/BookModel.msl;
provider=System.Data.SqlClient;provider connection string="data source=.\SQLEXPRESS;initial catalog=Test;
integrated security=SSPI;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" /> </connectionStrings> </configuration>