4

ASP.NET WebAPI 2 整合 NSwag

 2 years ago
source link: https://blog.darkthread.net/blog/use-nswag-on-aspnet-webapi2/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

ASP.NET WebAPI 2 整合 NSwag

2019-04-09 09:44 PM 14 5,711

前陣子介紹過用 Swashbuckle 為 ASP.NET WebAPI 產生 Swagger/OpenAPI 文件,可自動產生 Swagger UI 線上說明及測試介面,再配合 NSwag Studio 等工具自動產生客戶端,開發體驗不輸 WCF/Web Service。

但後來發現一件事,Swashbuckle 雖然歷史較久名氣較大,但作者兩年前重心已移往 ASP.NET Core,另起了 Swashbuckle.AspNetCore,ASP.NET WebAPI 版本已不再維護。此點讓我慎重評估另一個選項 - NSwag,它跟 Swashbuckle 一樣是 ASP.NET Core 官方文件列舉的 Swagger 解決方案。NSwag 專案同時支援 ASP.NET Core 及 OWIN Middleware,通吃 .NET Framework 與 .NET Core 版本 WebAPI。由於工作專案仍以 ASP.NET MVC/WebAPI 為主,但新的小型專案可能會用 ASP.NET Core,再加上客戶端程式庫產生器已決定採用 NSwag Studio,伺服器端統一改用 NSwag 似乎是個不錯的選擇。

如何在 ASP.NET Core 使用 NSwag,官方文件已有說明,在 ASP.NET WebAPI 整合 NSwag 的資料相對較少,在此整理新建 ASP.NET Web API 引用 NSwag 步驟以為日後參考。參考來源:NSwag OWIN Middleware

  1. 在 Visual Studio 新增 ASP.NET Web Application (.NET Framework) 專案 (以 VS2017 為例)

  2. 選擇 Web API 範本

  3. 規格沿用自範例教學:使用 ASP.NET MVC 打造 WebAPI 服務開發一加解密 Web API,核心邏輯照抄 Models/CodecModule.cs,提供 EncrytString()、DecryptData() 兩個方法。

  4. 新增 Web API 2 Controller - Empty

    CodecController.cs 內容如下,介面不走 RESTful,採 RPC-Style 以名稱區隔多個 HttpPost,這在 Swashbuckle 會遇到 Multiple operations with path 'api/MyApiName' and method 'POST' 錯誤,要以 [Route(api/...)] 在每個 Action 明確定義路由;NSwag 則在初始設定階段定義一次即可,簡單許多。

     using System.Collections.Generic;
     using System.Web.Http;
     using WebApiDemo.Models;
    
     namespace WebApiDemo.Controllers
     {
         public class CodecController : ApiController
         {
             /// <summary>
             /// 加密字串
             /// </summary>
             /// <param name="encKey">加密金鑰</param>
             /// <param name="rawText">明文字串</param>
             /// <returns>加密字串</returns>
             [HttpPost]
             public byte[] EncryptString(string encKey, string rawText)
             {
                 return CodecModule.EncrytString(encKey, rawText);
             }
    
             /// <summary>
             /// 解密請求參數物件
             /// </summary>
             public class DecryptParameter
             {
                 /// <summary>
                 /// 加密金鑰
                 /// </summary>
                 public string EncKey { get; set; }
                 /// <summary>
                 /// 加密字串陣列
                 /// </summary>
                 public List<byte[]> EncData { get; set; }
             }
    
             /// <summary>
             /// 批次解密
             /// </summary>
             /// <param name="decData">解密請求參數(加解密金鑰與加密字串陣列)</param>
             /// <returns>解密字串陣列</returns>
             [HttpPost]
             public List<string> BatchDecryptData([FromBody]DecryptParameter decData)
             {
                 return CodecModule.DecryptData(decData.EncKey, decData.EncData);
             }
         }
     }
    
    
  5. 接著用 NuGet 新增以下項目:

    • NSwag.AspNet.Owin
    • Microsoft.AspNet.WebApi.Owin
    • Microsoft.Owin.Host.SystemWeb

    安裝 NSwag.AspNet.Owin 時會一併安裝 Owin、Microsoft.Owin 等套件,但不包含 Microsoft.AspNet.WebApi.Owin 及 Microsoft.Owin.Host.SystemWeb,記得要額外加裝。

  6. 在專案新增 Startup.cs

    Startup.cs 內容如下:

     using Microsoft.Owin;
     using NSwag.AspNet.Owin;
     using Owin;
     using System.Web.Http;
    
     [assembly: OwinStartup(typeof(WebApiDemo.Startup))]
    
     namespace WebApiDemo
     {
         public class Startup
         {
             public void Configuration(IAppBuilder app)
             {
                 var config = new HttpConfiguration();
                 app.UseSwaggerUi3(typeof(Startup).Assembly, settings =>
                 {
                     //針對RPC-Style WebAPI,指定路由包含Action名稱
                     settings.GeneratorSettings.DefaultUrlTemplate = 
                         "api/{controller}/{action}/{id?}";
                     //可加入客製化調整邏輯
                     settings.PostProcess = document =>
                     {
                         document.Info.Title = "WebAPI 範例";
                     };                    
                 });
                 app.UseWebApi(config);
                 config.MapHttpAttributeRoutes();
                 config.EnsureInitialized();
             }
         }
     }
    
  7. 另外記得要開啟產生 XML 文件 Swagger UI 才會有方法及參數說明,Swashbuckle 需手工指定 XML 路徑,NSwag 會自己抓,再方便一些。

  8. 因為要將 URL /swagger/* 導向 NSwag 處理程式,web.config 需加入處理器設定:

     <system.webServer>
         ...
         <handlers>
             ...
             <add name="NSwag" path="swagger" verb="*" 
                  type="System.Web.Handlers.TransferRequestHandler" 
                  preCondition="integratedMode,runtimeVersionv4.0" />   
    
  9. 萬事齊備,執行網站,連上 ~/swagger 可在 Swagger UI 看到 WebAPI 項目並直接在網頁上測試:

【實測心得】NSwag 設定上較 Swashbuckle 簡單,尤其我採用 RPC-Style Web API,Swashbuckle 需在每個 Action 加註 [Route],NSwag 只需在 Startup.cs 設定。但主要考量點仍在於 ASP.NET WebAPI 版的 Swashbuckle 已不再維護,NSwag 專案則相對活躍,經評估,未來專案如需 WebAPI 文件、測試 UI、客戶端產生自動化解決方案,將以 NSwag 為主。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK