Web API文件產生器-Swagger

關於Web API 如何產生說明文件,本篇針對內建的help及目前微軟也在使用的Swagger作介紹。


一.內建說明

Web API的專案範本,內建會在Area加入一個help area幫你產生基本的文件說明,如下

輸出xml






加入註解

在HelpPageConfig.cs 加入xml路徑

  public static void Register(HttpConfiguration config)
  {
  string xmlHelpPath = HttpContext.Current.Server.MapPath("~/bin/WebApiSwaggerLab.xml");
  config.SetDocumentationProvider(new XmlDocumentationProvider(xmlHelpPath));
..


瀏覽/Help



二.使用Swagger

若你想產生文件比較漂亮點的,並可以即時測試,可以考處使用Swagger 

1.安裝nuget package

Install-Package Swashbuckle


2.加入xml說明檔來源
打開SwaggerConfig.cs,找到IncludeXmlComments,修改如下

c.IncludeXmlComments($@"{System.AppDomain.CurrentDomain.BaseDirectory}\bin\WebApiSwaggerLab.XML");

瀏覽http://localhost:port/swagger,會列出所有的API及說明

並可以直接輸入參數作測試

Swagger 其他調整

1.修改說明文件的回應型別
在測試時可以選擇回傳型別,如下圖預設會有四種
若你的明確指定回傳型別,可以調整如下,只回應jpg格式:



2.自訂首頁

Swagger在自訂UI的功能上,提供了自訂首頁、css、js等,本文挑選自訂首頁作說明
新增一檔案index.html放在Content目錄底下,html的內容從Swashbuckle Github上copy下來後,修改一下Logo名稱


將檔案屬性改成Embed Resource


打開SwaggerConfig.cs,找到EnableSwaggerUi ,加入CustomAsset,如下

 .EnableSwaggerUi(c =>
   {
    c.CustomAsset("index", thisAssembly, "WebApiSwaggerLab.Content.index.html");
..

執行結果



參考來源


這個網誌中的熱門文章

IIS 設定只允許特定IP進入