【swagger】C# 中 swagger 的使用及避坑

@

開發 web api 的時候,寫文檔是個痛苦的事情,而沒有文檔別人就不知道怎麼調用,所以又不得不寫。

swagger 可以自動生成接口文檔,並測試接口,極大的解放了程序員的生產力。

1 安裝

通過 NuGet 安裝 Swashbuckle。
在這裡插入圖片描述
安裝完成後,App_Start 文件夾下會多出一個 SwaggerConfig.cs 文件。
在這裡插入圖片描述
重新生成並發佈 api,打開網頁 http://localhost:7001/swagger(這裡注意換成你的 host)

網頁顯示如下:
在這裡插入圖片描述

2 修改名稱和版本號

上圖中框出的名稱和版本號是可以修改的,打開 SwaggerConfig.cs 文件,找到如下代碼:

c.SingleApiVersion("v1", "API.Test");  

修改其中的參數,重新發佈即可。

3 顯示說明

swagger 可以讀取代碼中的注釋,並顯示在網頁上。如此一來,我們只需要在代碼中將注釋寫好,就可以生成一份可供他人閱讀的 API 文檔了。

swagger 是通過編譯時生成的 xml 文件來讀取注釋的。這個 xml 文件默認是不生成的,所以先要修改配置。

第一步: 右鍵項目 -> 屬性 -> 生成,把 XML 文檔文件勾上。
在這裡插入圖片描述
第二步: 添加配置
在 SwaggerConfig.cs 文件中添加配置如下:

GlobalConfiguration.Configuration      .EnableSwagger(c =>          {              c.SingleApiVersion("v2", "測試 API 接口文檔");              // 配置 xml 文件路徑              c.IncludeXmlComments($@"{System.AppDomain.CurrentDomain.BaseDirectory}binAPI.Test.xml");          })  

注意:發佈的時候,XML 文件不會一起發佈,需要手動拷到發佈目錄下。

在這裡插入圖片描述

4 顯示控制器注釋及漢化

默認是不會顯示控制器注釋的,需要自己寫。
在 App_Start 中新建類 SwaggerControllerDescProvider,代碼如下:

/// <summary>  /// swagger 顯示控制器的描述  /// </summary>  public class SwaggerCacheProvider : ISwaggerProvider  {      private readonly ISwaggerProvider _swaggerProvider;      private static ConcurrentDictionary<string, SwaggerDocument> _cache = new ConcurrentDictionary<string, SwaggerDocument>();      private readonly string _xmlPath;        /// <summary>      ///      /// </summary>      /// <param name="swaggerProvider"></param>      /// <param name="xmlpath">xml文檔路徑</param>      public SwaggerCacheProvider(ISwaggerProvider swaggerProvider, string xmlpath)      {          _swaggerProvider = swaggerProvider;          _xmlPath = xmlpath;      }        public SwaggerDocument GetSwagger(string rootUrl, string apiVersion)      {          var cacheKey = string.Format("{0}_{1}", rootUrl, apiVersion);          //只讀取一次          if (!_cache.TryGetValue(cacheKey, out SwaggerDocument srcDoc))          {              srcDoc = _swaggerProvider.GetSwagger(rootUrl, apiVersion);                srcDoc.vendorExtensions = new Dictionary<string, object>              {                  { "ControllerDesc", GetControllerDesc() }              };              _cache.TryAdd(cacheKey, srcDoc);          }          return srcDoc;      }        /// <summary>      /// 從API文檔中讀取控制器描述      /// </summary>      /// <returns>所有控制器描述</returns>      public ConcurrentDictionary<string, string> GetControllerDesc()      {          ConcurrentDictionary<string, string> controllerDescDict = new ConcurrentDictionary<string, string>();          if (File.Exists(_xmlPath))          {              XmlDocument xmldoc = new XmlDocument();              xmldoc.Load(_xmlPath);                string[] arrPath;              int cCount = "Controller".Length;              foreach (XmlNode node in xmldoc.SelectNodes("//member"))              {                  string type = node.Attributes["name"].Value;                  if (type.StartsWith("T:"))                  {                      arrPath = type.Split('.');                      string controllerName = arrPath[arrPath.Length - 1];                      if (controllerName.EndsWith("Controller"))  //控制器                      {                          //獲取控制器注釋                          XmlNode summaryNode = node.SelectSingleNode("summary");                          string key = controllerName.Remove(controllerName.Length - cCount, cCount);                          if (summaryNode != null && !string.IsNullOrEmpty(summaryNode.InnerText) && !controllerDescDict.ContainsKey(key))                          {                              controllerDescDict.TryAdd(key, summaryNode.InnerText.Trim());                          }                      }                  }              }          }          return controllerDescDict;      }  }  

另外,新建 swagger.js 文件並將其設置成 嵌入的資源,這個文件的作用就是顯示控制器注釋及漢化。js 代碼如下:

'use strict';  window.SwaggerTranslator = {      _words: [],        translate: function () {          var $this = this;          $('[data-sw-translate]').each(function () {              $(this).html($this._tryTranslate($(this).html()));              $(this).val($this._tryTranslate($(this).val()));              $(this).attr('title', $this._tryTranslate($(this).attr('title')));          });      },        setControllerSummary: function () {          $.ajax({              type: "get",              async: true,              url: $("#input_baseUrl").val(),              dataType: "json",              success: function (data) {                  var summaryDict = data.ControllerDesc;                  var id, controllerName, strSummary;                  $("#resources_container .resource").each(function (i, item) {                      id = $(item).attr("id");                      if (id) {                          controllerName = id.substring(9);                          strSummary = summaryDict[controllerName];                          if (strSummary) {                              $(item).children(".heading").children(".options").first().prepend('<li class="controller-summary" title="' + strSummary + '">' + strSummary + '</li>');                          }                      }                  });              }          });      },      _tryTranslate: function (word) {          return this._words[$.trim(word)] !== undefined ? this._words[$.trim(word)] : word;      },        learn: function (wordsMap) {          this._words = wordsMap;      }  };      /* jshint quotmark: double */  window.SwaggerTranslator.learn({      "Warning: Deprecated": "警告:已過時",      "Implementation Notes": "實現備註",      "Response Class": "響應類",      "Status": "狀態",      "Parameters": "參數",      "Parameter": "參數",      "Value": "值",      "Description": "描述",      "Parameter Type": "參數類型",      "Data Type": "數據類型",      "Response Messages": "響應消息",      "HTTP Status Code": "HTTP 狀態碼",      "Reason": "原因",      "Response Model": "響應模型",      "Request URL": "請求 URL",      "Response Body": "響應體",      "Response Code": "響應碼",      "Response Headers": "響應頭",      "Hide Response": "隱藏響應",      "Headers": "頭",      "Try it out!": "試一下!",      "Show/Hide": "顯示/隱藏",      "List Operations": "顯示操作",      "Expand Operations": "展開操作",      "Raw": "原始",      "can't parse JSON.  Raw result": "無法解析 JSON。原始結果",      "Model Schema": "模型架構",      "Model": "模型",      "apply": "應用",      "Username": "用戶名",      "Password": "密碼",      "Terms of service": "服務條款",      "Created by": "創建者",      "See more at": "查看更多:",      "Contact the developer": "聯繫開發者",      "api version": "api 版本",      "Response Content Type": "響應 Content Type",      "fetching resource": "正在獲取資源",      "fetching resource list": "正在獲取資源列表",      "Explore": "瀏覽",      "Show Swagger Petstore Example Apis": "顯示 Swagger Petstore 示例 Apis",      "Can't read from server.  It may not have the appropriate access-control-origin settings.": "無法從服務器讀取。可能沒有正確設置 access-control-origin。",      "Please specify the protocol for": "請指定協議:",      "Can't read swagger JSON from": "無法讀取 swagger JSON於",      "Finished Loading Resource Information. Rendering Swagger UI": "已加載資源信息。正在渲染 Swagger UI",      "Unable to read api": "無法讀取 api",      "from path": "從路徑",      "server returned": "服務器返回"  });  $(function () {      window.SwaggerTranslator.translate();      window.SwaggerTranslator.setControllerSummary();  });  

在 SwaggerConfig.cs 添加如下配置:

GlobalConfiguration.Configuration      .EnableSwagger(c =>          {              c.CustomProvider((defaultProvider) => new SwaggerCacheProvider(defaultProvider, $@"{System.AppDomain.CurrentDomain.BaseDirectory}binAPI.Test.xml"));          })          .EnableSwaggerUi(c =>              {                  c.InjectJavaScript(System.Reflection.Assembly.GetExecutingAssembly(), "API.Test.swagger.js");              });  

5 路由相同,查詢參數不同的方法

在實際的 ASP.NET Web API 中,是可以存在 路由相同HTTP 方法相同查詢參數不同 的方法的,但不好意思,swagger 中不支持,並且會直接報錯。

如下代碼,

[Route("api/users")]  public IEnumerable<User> Get()  {      return users;  }    [Route("api/users")]  public IEnumerable<User> Get(int sex)  {      return users;  }  

報錯: Multiple operations with path ‘api/users’ and method ‘GET’.

在這裡插入圖片描述
可以在 SwaggerConfig.cs 添加如下配置:

GlobalConfiguration.Configuration      .EnableSwagger(c =>          {              c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());          })  

此配置的意思是,當遇到此種情況時,取第一個方法展示。

這可以避免報錯,但多個方法只會在 swagger 中展示一個。治標不治本,不推薦。所以唯一的解決方案就是設置成不同的路由。不知道這個問題在之後的版本中會不會修復。

6 忽略 Model 中的某些字段

如下圖,新建用戶時,後台需要一個 User 類作為參數。點擊右側的 Model,可以顯示 User 類的屬性及注釋。
在這裡插入圖片描述
但是,有些字段其實是無需調用者傳遞的。例如 State,調用者無需知道這些字段的存在。

給這些屬性標記上 [Newtonsoft.Json.JsonIgnore] 特性,swagger 中不再顯示了。

當然這種做法也是有缺點的,因為 web api 在返回數據時,調用的默認序列化方法也是 Newtonsoft.Json 序列化。

7 傳遞 header

調用 api 時,有些信息是放在 HTTP Header 中的,例如 token。這個 swagger 也是支持的。

新建一個特性:

public class ApiAuthorizeAttribute : Attribute  {    }  

新建一個類代碼如下:

public class AuthorityHttpHeaderFilter : IOperationFilter  {      public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)      {          if (operation.parameters == null)              operation.parameters = new List<Parameter>();            //判斷是否添加權限過濾器            var isAuthorized = apiDescription.ActionDescriptor.GetCustomAttributes<ApiAuthorizeAttribute>().Any();          if (isAuthorized)          {              operation.parameters.Add(new Parameter { name = "token", @in = "header", description = "令牌", required = false, type = "string" });          }      }  }  

這段代碼就是告訴 swagger,如果遇到的方法上標記了 ApiAuthorizeAttribute 特性,則添加一個名為 token 的參數在 header 中。

最後需要在 SwaggerConfig.cs 中註冊這個過濾器。

GlobalConfiguration.Configuration      .EnableSwagger(c =>          {              c.OperationFilter<AuthorityHttpHeaderFilter>();          })  

效果如下:
在這裡插入圖片描述

8 出錯時的 HTTP 狀態碼

我們在方法中返回一個 400

[Route("api/users")]  public HttpResponseMessage Post([FromBody]User user)  {      return new HttpResponseMessage()      {          Content = new StringContent("新建用戶出錯", Encoding.UTF8, "application/json"),          StatusCode = HttpStatusCode.BadRequest      };  }  

可是,swagger 中返回的狀態碼卻是 0。
在這裡插入圖片描述
這是因為 Content 指定了 JSON 格式,但傳入的 content 又不是 JSON 格式的。

content 改為 JSON 格式,或者將 mediaType 改成 text/plain 就可以了。