封裝WebAPI客戶端,附贈Nuget打包上傳VS拓展工具


一、前言

上篇《 WebAPI使用多個xml文件生成幫助文檔 》有提到為什么會出現基於多個xml文件生成幫助文檔的解決方案,因為定義的模型可能的用處有:

1:單元測試

2:其他項目引用(可能以Nuget包的形式)

3:WebAPI客戶端(封裝的HttpClient及WebAPI接口調用,其實包含在第2點內..)

 

要源碼的可以直接拉到最下面,源碼一如既往的還在那

二、為什么要封裝WebAPI客戶端

1:讓WebAPI對於調用者來說“透明”,直接以引用程序集的方式。

2:統一項目內調用入口(當然了,非要繞過直接去請求接口肯定也是可以得,但是這是團隊管理的問題)。

3:組合接口調用

4:版本化(通過Nuget,不論是自建還是Nuget.org)

三、封裝的WebAPI客戶端都包含些什么

這里繼續使用 WebAPI2PostMan 項目來演示。

首先,因為將WebAPI的接口以HttpClient來進行封裝,那至少需要定義出接口的請求路由,此處僅定義出了兩處。

我們在解決方案新建一個類庫項目,並將其命名為 WebAPI2PostMan.Client ,接着添加一個名為 WebApi2PostManStatic 的類

using System.Configuration;

namespace WebAPI2PostMan.Client
{
    /// <summary>
    ///     WebApi2PostMan靜態資源類
    /// </summary>
    public class WebApi2PostManStatic
    {
        /// <summary>
        ///     服務地址
        /// </summary>
        public static string ServiceUrl = ConfigurationManager.AppSettings["WebAPI2PostManServiceUrl"];
        /// <summary>
        ///     獲取所有產品
        /// </summary>
        public static string RouteProductGetAll = "api/Product/All";
        /// <summary>
        ///     添加產品
        /// </summary>
        public static string RouteProductAdd = "api/Product/Add";
    }
}

接口請求無非就是Http的那幾個方法,但此處僅認為我們的接口只包含Get和Post兩種Http請求方法。

基於此,我們定義出一個WebApiHelper類。

/// <summary>
///     WebAPI幫助類
/// </summary>
public class WebApiHelper
{
    public static T1 CallPostWebApi<T1, T2>(string url, T2 request, string serviceUrl, int? timeOut = 10)
    

    public static T1 CallGetWebApi<T1>(string url, string serviceUrl, int? timeOut = 10)
   

    public static List<TResponse> CallWebApiBatch<TRequest, TResponse>(HttpMethod method, string endpoint, List<TRequest> batchRequestModels, string url, string serviceUrl, int? timeOut = 10)
    

    public static async Task<T1> CallPostWebApiAsync<T1, T2>(string url, T2 request, string serviceUrl, int? timeOut = 10)
   

    public static async Task<T1> CallGetWebApiAsync<T1>(string url, string serviceUrl, int? timeOut = 10)
   

    public static async Task<List<TResponse>> CallWebApiBatchAsync<TRequest, TResponse>(HttpMethod method,string endpoint,List<TRequest> batchRequestModels,string url,string serviceUrl,int? timeOut=10)
}

為了節省篇幅和便於觀看,將實現都刪去了,可以看到定義了6個方法,分為同步和異步一共三類,Get , Post ,Batch(批量接口,有感興趣的就下篇講講)。

然后,再添加一個用於封裝的類 WebApi2PostManClient。

using System.Collections.Generic;
using WebAPI2PostMan.WebModel;

namespace WebAPI2PostMan.Client
{
    /// <summary>
    ///     WebApi2PostMan 客戶端
    /// </summary>
    public class WebApi2PostManClient
    {
        /// <summary>
        ///     獲取所有產品
        /// </summary>
        /// <param name="timeout">超時時間</param>
        /// <returns>產品列表</returns>
        public static IEnumerable<Product> GetAllProduct(int? timeout = 10)
        {
            return WebApiHelper.CallGetWebApi<IEnumerable<Product>>(WebApi2PostManStatic.RouteProductGetAll,WebApi2PostManStatic.ServiceUrl,timeout);
        }
        /// <summary>
        ///     添加產品
        /// </summary>
        /// <param name="request">添加的產品</param>
        /// <param name="timeout">超時時間</param>
        /// <returns>添加結果</returns>
        public static string AddProduct(Product request,int? timeout = 10)
        {
            return WebApiHelper.CallPostWebApi<string, Product>(WebApi2PostManStatic.RouteProductAdd, request,WebApi2PostManStatic.ServiceUrl, timeout);
        }
    }
}

四、使用Nuget包管理器來發布WebAPI2PostMan.Client

怎么搭建NugetServer就不贅述了,新建一個空的web項目接着程序包控制台輸入

PM> Install-Package NuGet.Server

然后該有的都會有了,直接發布到IIS即可。

此時,本地已經有一個NugetServer了,瀏覽如下。

image

右鍵項目 WebAPI2PostMan.Client => 屬性 => 應用程序 => 程序集信息,補全一些信息。

image

運行命令行並定位到當前項目目錄,執行

nuget pack WebAPI2PostMan.Client.csproj -s http://localhost:88 123

此處的nuget是配的環境變量,也可以替換成( 路徑/NuGet.exe ),若啟用了 NuGet 程序包還原的話,解決方案目錄下的文件夾.nuget內會有NuGet.exe及其配置。

http://localhost:88 即為server地址,此處切不可加/nuget,否則會報403. 后面是密碼,默認沒設置的話會有警告並提示使用nuget setApiKey 設置。

那么其實一直以來都是做一個批處理腳本來打包並上傳我們的包。

或者是dudu很久以前發的《用Nuget管理好自家的包包i》以及 http://www.cnblogs.com/lzrabbit/tag/NuGet/ 講的都很詳細。

還有《將nuget與VS直接集成,實現一鍵上傳等功能》,只不過是需要手動設置的。

為了不想這么麻煩,順手寫了一個VS的拓展工具 Push2NuGet 來簡化這些操作。

首先在 工具=》拓展和更新=》聯機=》Visual Studio庫 =》輸入 Push2NuGet 安裝,重啟解決方案。

image

因為是一口氣寫出來的,沒想好 一些服務參數放哪,就暫時扔到.nuget文件夾下,因此,需要在.nuget文件夾下 新建一個NuGet.xml的文件並完善信息。

<?xml version="1.0" encoding="utf-8"?>
<SelfServer>
  <Url>http://localhost:88</Url>
  <ApiKey>123</ApiKey>
</SelfServer>

然后右鍵項目點擊【打包並上傳】即可。

成功后顯示。

image

新建一個 單元測試項目 WebAPI2PostMan.Tests 並在Nuget里設置Nuget源。

image

安裝剛才上傳的 WebAPI2PostMan.Client

image

添加兩個單元測試方法

image

五、源碼

示例源碼:https://github.com/yanghongjie/WebAPI2PostMan

拓展工具:https://github.com/yanghongjie/Push2NugetServer

既然都看到這了,順手評價再賞個推薦唄!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM