WCF學習之旅—實現支持REST服務端應用(二十三)

来源:http://www.cnblogs.com/chillsrc/archive/2016/08/30/5821099.html
-Advertisement-
Play Games

在上一篇(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=&quot;data source=.\SQLEXPRESS;initial catalog=Test;
integrated security=SSPI;MultipleActiveResultSets=True;App=EntityFramework&quot;"
providerName="System.Data.EntityClient" /> </connectionStrings> </configuration>

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 從淘寶UWP第一版發佈到現在,已經有十個月了,期間收到了用戶各種各樣的反饋,感謝這些用戶的反饋,指導我們不斷的修正、完善應用。但是也有一部分需求或建議,由於資源或技術的限制,目前確實無法做到,只能對廣大Win10er說聲抱歉了。下麵針對幾種用戶常提到的反饋做下說明。 最經常的反饋是為什麼在某某版本上 ...
  • 序列 延遲查詢執行 查詢操作符 查詢表達式 表達式樹 (一) 序列 先上一段代碼, 這段代碼使用擴展方法實現下麵的要求: 取進程列表,進行過濾(取大於10M的進程) 列表進行排序(按記憶體占用) 只保留列表中指定的信息(ID,進程名) 為了能清楚理解上面代碼的內部動作,我們需要介紹幾組概念. 1. I ...
  • 模塊是平臺功能的單元,是源碼和數據的集合體。模塊管理(菜單、動作、數據)是整個平臺中框架功能體現的核心。整個平臺內的各個功能模塊都是在此進行配置的。 ...
  • 1. 條件運算符(?:)根據Boolean表達式的值返回兩個值之一。表達式如下: condition ? first_expression : second_expression 2. $""替代String.Format()方法,""中包含字元,有變數的需要用{}括起: 舉例 if (bonus= ...
  • C#對象序列化與反序列化(轉載自:http://www.cnblogs.com/LiZhiW/p/3622365.html) 1. 對象序列化的介紹.................................................................... 2 (1) .... ...
  • [雖然說,開發的時候,我們可以使用各種框架,ado.net作為底層的東西,作為一個合格的程式員,在出問題的時候我們還是要知道如何調試] 一、增刪改查 cmd.ExecuteReader();執行查詢,所有sql語句的查詢都用這個方法; cmd.ExecuteNonQuery();執行所有sql語句的 ...
  • RiderRS 扯淡:很多人說:jetbrains出品,必屬精品,jetbrains確實出了不少好東西,但是他的產品總感覺越用越慢,我的小Y430P高配版也倍感壓力,記憶體占用率高。 Multiple runtime support Project Rider supports the .NET Fr ...
  • 前戲:入園這麼久,第一次這麼認真的寫博客,先自我介紹下,我是一隻存活在C#陣營的老菜鳥了,主要的在C#陣營瞎忽悠,然後走走其他陣營,工作已經要有6年了,目前還在蘇州混,然後確沒啥大的技術性突破,時間和精力也都有限,所以一直這麼菜下去。話說,最近整理我的硬碟,發現前年自己接的一個項目,關於“水廠管理軟 ...
一周排行
    -Advertisement-
    Play Games
  • 前言 本文介紹一款使用 C# 與 WPF 開發的音頻播放器,其界面簡潔大方,操作體驗流暢。該播放器支持多種音頻格式(如 MP4、WMA、OGG、FLAC 等),並具備標記、實時歌詞顯示等功能。 另外,還支持換膚及多語言(中英文)切換。核心音頻處理採用 FFmpeg 組件,獲得了廣泛認可,目前 Git ...
  • OAuth2.0授權驗證-gitee授權碼模式 本文主要介紹如何筆者自己是如何使用gitee提供的OAuth2.0協議完成授權驗證並登錄到自己的系統,完整模式如圖 1、創建應用 打開gitee個人中心->第三方應用->創建應用 創建應用後在我的應用界面,查看已創建應用的Client ID和Clien ...
  • 解決了這個問題:《winForm下,fastReport.net 從.net framework 升級到.net5遇到的錯誤“Operation is not supported on this platform.”》 本文內容轉載自:https://www.fcnsoft.com/Home/Sho ...
  • 國內文章 WPF 從裸 Win 32 的 WM_Pointer 消息獲取觸摸點繪製筆跡 https://www.cnblogs.com/lindexi/p/18390983 本文將告訴大家如何在 WPF 裡面,接收裸 Win 32 的 WM_Pointer 消息,從消息裡面獲取觸摸點信息,使用觸摸點 ...
  • 前言 給大家推薦一個專為新零售快消行業打造了一套高效的進銷存管理系統。 系統不僅具備強大的庫存管理功能,還集成了高性能的輕量級 POS 解決方案,確保頁面載入速度極快,提供良好的用戶體驗。 項目介紹 Dorisoy.POS 是一款基於 .NET 7 和 Angular 4 開發的新零售快消進銷存管理 ...
  • ABP CLI常用的代碼分享 一、確保環境配置正確 安裝.NET CLI: ABP CLI是基於.NET Core或.NET 5/6/7等更高版本構建的,因此首先需要在你的開發環境中安裝.NET CLI。這可以通過訪問Microsoft官網下載並安裝相應版本的.NET SDK來實現。 安裝ABP ...
  • 問題 問題是這樣的:第三方的webapi,需要先調用登陸介面獲取Cookie,訪問其它介面時攜帶Cookie信息。 但使用HttpClient類調用登陸介面,返回的Headers中沒有找到Cookie信息。 分析 首先,使用Postman測試該登陸介面,正常返回Cookie信息,說明是HttpCli ...
  • 國內文章 關於.NET在中國為什麼工資低的分析 https://www.cnblogs.com/thinkingmore/p/18406244 .NET在中國開發者的薪資偏低,主要因市場需求、技術棧選擇和企業文化等因素所致。歷史上,.NET曾因微軟的閉源策略發展受限,儘管後來推出了跨平臺的.NET ...
  • 在WPF開發應用中,動畫不僅可以引起用戶的註意與興趣,而且還使軟體更加便於使用。前面幾篇文章講解了畫筆(Brush),形狀(Shape),幾何圖形(Geometry),變換(Transform)等相關內容,今天繼續講解動畫相關內容和知識點,僅供學習分享使用,如有不足之處,還請指正。 ...
  • 什麼是委托? 委托可以說是把一個方法代入另一個方法執行,相當於指向函數的指針;事件就相當於保存委托的數組; 1.實例化委托的方式: 方式1:通過new創建實例: public delegate void ShowDelegate(); 或者 public delegate string ShowDe ...