Swagger 是一個可以將 WebAPI 快速文件化的套件,產生出來的線上文件除了可以列出 API 詳細資料外還可以直接在網頁上進行測試的動作,對開發者和接 API 的使用者來說十分方便,上一篇文章介紹了 Swagger 基本使用 說明,最近想要在公司內部推廣使用 Swagger 服務,資深同事提到過去有陣子曾經使用過 Swagger 服務,但 每次要使用 API 接口服務時參數 (params) 資訊都要重新輸入 ,有點麻煩用一陣子之後大家就回去使用 Postman 了,了解後發現的確在測試時會花時間在輸入測試資料,如果測試環境測試資料都是固定的,就可省下輸入資料的時間更可避免 key 錯資料的狀況發生 ( 參考下方 gif 檔案)這邊文章記錄解決此問題的過程
解決方案
Swagger 在產生 API 接口的 Model 時取得該物件的 properties 及其對應型別,將其物件資訊顯示在 html文件上,但不會生成 "可以測試的真實數據 (或是你想要的)" 資料,也就是說替換下圖的紅色框框資料,讓它是有意義的資料,搜尋後發現可以使用 Swashbuckle.Examples 來滿足我們小小的需求,以下整理研究後的步驟與使用說明
安裝 Swashbuckle.Examples
Step 2. 目前最新版是 3.10.0 且不會額外下載其他特別的 dll > 下一步
Step 3. 可以到專案參考是否有 Swashbuckle.Examples dll,有的話就是下載完成
實作 Request Sample
接者新增 UserExample 類別並實作 IExamplesProvider 介面,並將我們指定的測試資料定義在該介面的 GetExample 方法中
- [SwaggerRequestExample(typeof(Users), typeof(UserExample))]
- public IHttpActionResult Login(Users input)
完整的 Code 請參考
- public class UserExample : IExamplesProvider
- {
- public object GetExamples()
- {
- return new Users
- {
- Account = "marcus",
- Password = "123456",
- Key = 9487,
- };
- }
- }
設定 SwaggerConfig
- public class HomeController : ApiController
- {
- [Route("Login")]
- [SwaggerRequestExample(typeof(Users), typeof(UserExample))]
- public IHttpActionResult Login(Users input)
- {
- var rep = new ResponseObject();
- if (input.Account == "marcus"
- && input.Password == "123456"
- && input.Key == 9487)
- {
- rep.Code = "000";
- rep.Message = "Success";
- rep.Token = Guid.NewGuid();
- }
- else
- {
- rep.Code = "999";
- rep.Message = "Please check your input params";
- }
- return Ok(rep);
- }
- }
- public class Users
- {
- public string Password { get; set; }
- public string Account { get; set; }
- public int Key { get; set; }
- }
- public class UserExample : IExamplesProvider
- {
- public object GetExamples()
- {
- return new Users
- {
- Account = "marcus",
- Password = "123456",
- Key = 9487,
- };
- }
- }
- public class ResponseObject
- {
- public string Code { get; set; }
- public string Message { get; set; }
- public Guid Token { get; set; }
- }
打完收工
Swashbuckle.Examples 在使用上簡單容易上手,但除了可以透過此套件定義 Example Request Model 之外,官網文件上與有提到可以設定 Example Response Model、Description、Authorization...等更多資訊,也支持 .NET Core 版本,如果有需要各位大大也可以自行研究看看
這問題聽到當下嚇到吃手手,江湖上常聽到攻城屍很懶惰但沒想到懶到這程度,但仔細了解後發現問題確實存在,且驗證後發現,在此範例三個參數使用完整整省去一半的時間 18 sec > 9sec,想到之前參加研討會講師所講的,懶是一個美德,否則會局限自己的成長
參考
Swashbuckle.Examples
Swashbuckle Pro Tips for ASP.NET Web API – Example(s) Using AutoFixture
Swagger for Web API Document – Part Ⅱ
0 意見:
張貼留言