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
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...