環境: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 中的下面這一行的註解
c.IncludeXmlComments(GetXmlCommentsPath());
在同一個 Class ( public class SwaggerConfig ) 下增加方法
internal static string GetXmlCommentsPath()
{
//透過設定專案的屬性,設定在建置後生成 XmlDocument.xml,
//此處是設定 Swagger 參考這份 xml
return string.Format(@"{0}\App_Data\XmlDocument.xml",
System.AppDomain.CurrentDomain.BaseDirectory);
}
圖上刪了很多原本是註解掉的部份
設定專案屬性,右鍵點專案 > 專案屬性 > 建置頁籤 > 輸出
有一個 XML 文件檔案,勾選並設定檔案的路徑,這個路徑需要和前一步設定
的 XML 路徑對應。
/// <summary>
/// 人員
/// </summary>
public class Person
{
/// <summary>
/// 人員名稱
/// </summary>
public string Name { get; set; }
/// <summary>
/// 人員年紀
/// </summary>
public int Age { get; set; }
}
/// <summary>
/// 錯誤狀態
/// </summary>
public class ErrorStatus
{
/// <summary>
/// 狀態代碼
/// </summary>
public string StatusCode { get; set; }
/// <summary>
/// 狀態描述
/// </summary>
public string Description { get; set; }
}
public class PeopleController : ApiController
{
/// <summary>
/// 取得人員資料
/// </summary>
/// <remarks>
/// 取得人員資料 api 的補充說明
/// </remarks>
/// <param name="id">人員 Id</param>
/// <response code="200">成功</response>
/// <response code="404">找不到</response>
/// <response code="500">內部伺服器錯誤</response>
[ResponseType(typeof(Person))]
public IHttpActionResult Get(string id)
{
return Ok(new Person());
}
}
如果設定了 [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>
public class PeopleController : ApiController
{
/// <summary>
/// 取得人員資料
/// </summary>
/// <remarks>
/// 取得人員資料 api 的補充說明
/// </remarks>
/// <param name="id">人員 Id</param>
[SwaggerResponse(HttpStatusCode.OK, Description = "成功", Type = typeof(Person))]
[SwaggerResponse(HttpStatusCode.NotFound, Description = "找不到")]
[SwaggerResponse(HttpStatusCode.InternalServerError, Description = "內部伺服器錯誤", Type = typeof(ErrorStatus))]
[ResponseType(typeof(Person))]
public IHttpActionResult Get(string id)
{
return Ok(new Person());
}
}




