2018年6月20日 星期三

Swashbuckle (1) 基本使用

環境:vs2017、.net framework 4.7、Swashbuckle 5.6.0

Swashbuckle,其實就是 Swagger,基本上是一套產生線上 API
文件的產生器,線上文件(網頁)同時也可以產生一個呼叫 API 的頁面。

在實際使用上有很多不同的進階選項可以使用,本篇只說明最基礎的部份。

建立一個 WebApi 專案,在專案中建立 PeopleController

    PeopleController.cs

  1. public class PeopleController : ApiController
  2. {
  3.     /// <summary>
  4.     /// 取得人員資料
  5.     /// </summary>
  6.     /// <returns></returns>
  7.     public string Get(string id)
  8.     {
  9.         return ("Ricky");
  10.     }
  11.     /// <summary>
  12.     /// 新增人員資料
  13.     /// </summary>
  14.     /// <returns></returns>
  15.     public HttpResponseMessage Post(Person person)
  16.     {
  17.         return Request.CreateResponse(
  18.             HttpStatusCode.Created, new { Status = "OK" });
  19.     }
  20. }
  21.  
  22.  
  23. public class Person
  24. {
  25.     public string Name { get; set; }
  26.     public int Age { get; set; }
  27. }

透過 Nuget 安裝套件 Swashbuckle 和 Swashbuckle.Core Swashbuckle 相依於 Swashbuckle.Core 所以實際上裝 Swashbuckle 另 一個會自已裝好。
安裝好後直接執行專案

然後網址輸入 http://localhost:xxxxx/swagger,就能開啟 WebApi 文件的介面



輸入好參數(如果該 api 需要),點下面的 try out 就能呼叫 api

以上就是最基本的使用部份,Swashbuckle 依照 Api Controlle 中的基本資訊
(ex. 參數、回傳值)等,生成頁面上的資訊,但諸如方法上的 <summary> 註解
等都不會反應到頁面上。

沒有留言:

張貼留言