2018年6月21日 星期四

Swashbuckle (3) 顯示 webapi 方法上 xml 的摘要

設定在 swagger 頁面顯示的 xml 摘要資訊

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

首先建立好一個 WebApi 專案和透過 Nuget 裝好 Swashbuckle,並且透過
http://localhost:xxxxx/swagger 能夠進到 Swashbuckle 的頁面。

本篇的目的在於讓 Api 上面的 xml 註解中的資訊出現在 swagger 的頁面上

在安裝好 swashbuckle 後開啟 App_Start 中的 SwaggerConfig.cs,這個檔案
應該在 Nuget 安裝好 Swashbuckle 時就自動產生。

取消 SwaggerConfig.cs 中的下面這一行的註解

  1. c.IncludeXmlComments(GetXmlCommentsPath());

在同一個 Class ( public class SwaggerConfig ) 下增加方法

  1. internal static string GetXmlCommentsPath()
  2. {
  3. //透過設定專案的屬性,設定在建置後生成 XmlDocument.xml,
  4. //此處是設定 Swagger 參考這份 xml
  5. return string.Format(@"{0}\App_Data\XmlDocument.xml",
  6. System.AppDomain.CurrentDomain.BaseDirectory);
  7. }

圖上刪了很多原本是註解掉的部份



設定專案屬性,右鍵點專案 > 專案屬性 > 建置頁籤 > 輸出

有一個 XML 文件檔案,勾選並設定檔案的路徑,這個路徑需要和前一步設定
的 XML 路徑對應。


WebApi 的例子
  1. /// <summary>
  2. /// 人員
  3. /// </summary>
  4. public class Person
  5. {
  6. /// <summary>
  7. /// 人員名稱
  8. /// </summary>
  9. public string Name { get; set; }
  10. /// <summary>
  11. /// 人員年紀
  12. /// </summary>
  13. public int Age { get; set; }
  14. }
  15.  
  16. /// <summary>
  17. /// 錯誤狀態
  18. /// </summary>
  19. public class ErrorStatus
  20. {
  21. /// <summary>
  22. /// 狀態代碼
  23. /// </summary>
  24. public string StatusCode { get; set; }
  25. /// <summary>
  26. /// 狀態描述
  27. /// </summary>
  28. public string Description { get; set; }
  29. }

  1. public class PeopleController : ApiController
  2. {
  3. /// <summary>
  4. /// 取得人員資料
  5. /// </summary>
  6. /// <remarks>
  7. /// 取得人員資料 api 的補充說明
  8. /// </remarks>
  9. /// <param name="id">人員 Id</param>
  10. /// <response code="200">成功</response>
  11. /// <response code="404">找不到</response>
  12. /// <response code="500">內部伺服器錯誤</response>
  13. [ResponseType(typeof(Person))]
  14. public IHttpActionResult Get(string id)
  15. {
  16. return Ok(new Person());
  17. }
  18. }

如果設定了 [ResponseType(typeof(Person))] 因為他預設是在 Http Status 200
的時候所回傳的類別,所以需要同時設定 <response code="200">成功</response>
才會正常顯示 [ResponseType(typeof(Person))] 的部份

在傳入值或回傳值,切換到 Model 下時會顯示定義在 DataModel 上的 <summary> 訊息

執行專案,然後接下來進到 Swagger 頁面就可以看到 webapi 上設定的 xml 註解的資訊


在比較新版的 Swashbuckle 中,可以利用 SwaggerResponse 這個 attribute 來取代
<response code=""></response>

  1. public class PeopleController : ApiController
  2. {
  3. /// <summary>
  4. /// 取得人員資料
  5. /// </summary>
  6. /// <remarks>
  7. /// 取得人員資料 api 的補充說明
  8. /// </remarks>
  9. /// <param name="id">人員 Id</param>
  10. [SwaggerResponse(HttpStatusCode.OK, Description = "成功", Type = typeof(Person))]
  11. [SwaggerResponse(HttpStatusCode.NotFound, Description = "找不到")]
  12. [SwaggerResponse(HttpStatusCode.InternalServerError, Description = "內部伺服器錯誤", Type = typeof(ErrorStatus))]
  13. [ResponseType(typeof(Person))]
  14. public IHttpActionResult Get(string id)
  15. {
  16. return Ok(new Person());
  17. }
  18. }


沒有留言:

張貼留言