參考文檔: https://www.cnblogs.com/liaods/p/10101513.html https://www.cnblogs.com/zyz-Notes/p/12030281.html 本示例使用MVC項目做演示(不推薦,推薦直接用WebAPI),框架版本使用 4.6.2 為了支 ...
參考文檔:
https://www.cnblogs.com/liaods/p/10101513.html
https://www.cnblogs.com/zyz-Notes/p/12030281.html
本示例使用MVC項目做演示(不推薦,推薦直接用WebAPI),框架版本使用 4.6.2
為了支持WebAPI,我們需要把當前的MVC項目改造一下,右鍵項目,通過 Nuget添加WebAPI的支持
在 App_Start 文件夾下添加 WebApiConfig 類
1 public class WebApiConfig 2 { 3 public static void Register(HttpConfiguration config) 4 { 5 // Web API 配置和服務 7 // Web API 路由 8 config.MapHttpAttributeRoutes(); 9 10 config.Routes.MapHttpRoute( 11 name: "DefaultApi", 12 routeTemplate: "api/{controller}/{action}/{id}", 13 defaults: new { id = RouteParameter.Optional } 14 ); 17 var jsonFormatter = new JsonMediaTypeFormatter(); 20 //jsonFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; 23 } 24 }
然後在全局中註冊改文件,代碼放到第二行,接下來就可以使用了
右鍵項目安裝: Swashbuckle 版本 5.6.0
安裝成功之後,在App_Start文件夾下多了一個文件:SwaggerConfig.cs
打開全局視圖 _Layout.cshtml,在裡邊添加一個鏈接:
<li>@Html.ActionLink("Swagger Help", "", "Swagger", new { area = "" }, null)</li>
直接運行,效果如下:
添加一個測試介面,UserInfoController
1 public class UserInfoController : BaseController 2 { 3 /// <summary> 4 /// GET: 用戶信息首頁介面 5 /// </summary> 6 /// <remarks> 7 /// 我是備註信息 8 /// </remarks> 9 /// <returns>我是返回信息</returns> 10 [HttpGet] 11 public IHttpActionResult Index() 12 { 13 return Json("Hello World"); 14 } 15 }
如下圖所示,介面顯示出來了,但都是英文,備註信息也沒有顯示出來,後邊解決
點擊按鈕: “Try It out”,會返回該介面內容
接下來,我們解決備註不顯示的問題,項目右鍵-->屬性,在 生成 選項卡中勾選 xml文檔文件選項。
然後打開 SwaggerConfig.cs 類,找到函數: c.IncludeXmlComments(GetXmlCommentsPath()) ,放開該行代碼註釋
並添加方法:GetXmlCommentsPath()
/// <summary> /// 獲取文檔路徑 /// </summary> /// <returns></returns> static string GetXmlCommentsPath() { return $@"{System.AppDomain.CurrentDomain.BaseDirectory}\bin\Swagger.Mvc.xml"; }
現在註釋信息顯示出來了,但是其他的地方還是英文
添加漢化支持,添加自定義漢化腳本,右鍵項目,添加文件夾 Swagger,添加js腳本文件 swagger_lang.js,右鍵該腳本文件,在屬性中的生成操作改為嵌入的資源
複製如下腳本:
///<summary> /// 中文轉換 ///</summary> var SwaggerTranslator = (function () { //定時執行檢測是否轉換成中文,最多執行500次 即500*50/1000=25s var iexcute = 0, //中文語言包 _words = { "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": "從路徑", "Click to set as parameter value": "點擊設置參數", "server returned": "伺服器返回" }, //定時執行轉換 _translator2Cn = function () { if ($("#resources_container .resource").length > 0) { _tryTranslate(); } if ($("#explore").text() == "Explore" && iexcute < 500) { iexcute++; setTimeout(_translator2Cn, 50); } }, //設置控制器註釋 _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").prepend('<li class="controller-summary" title="' + strSummary + '">' + strSummary + '</li>'); } } }); } }); }, //嘗試將英文轉換成中文 _tryTranslate = function () { $('[data-sw-translate]').each(function () { $(this).html(_getLangDesc($(this).html())); $(this).val(_getLangDesc($(this).val())); $(this).attr('title', _getLangDesc($(this).attr('title'))); }); }, _getLangDesc = function (word) { return _words[$.trim(word)] !== undefined ? _words[$.trim(word)] : word; }; return { Translator: function () { document.title = "API描述文檔"; $('body').append('<style type="text/css">.controller-summary{color:#10a54a !important;word-break:keep-all;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:250px;text-align:right;cursor:default;} </style>'); $("#logo").html("介面描述").attr("href", "/Home/Index"); //設置控制器描述 _setControllerSummary(); _translator2Cn(); } } })(); //執行轉換 SwaggerTranslator.Translator();
打開 SwaggerConfig.cs 類 ,找到函數:InjectJavaScript,並修改成上邊自定義的js文件路徑,格式用點分開
c.InjectJavaScript(thisAssembly, "Swagger.Mvc.Swagger.swagger_lang.js");
添加控制器描述和介面文檔緩存
1 public class CachingSwaggerProvider : ISwaggerProvider 2 { 3 private static ConcurrentDictionary<string, SwaggerDocument> _cache = 4 new ConcurrentDictionary<string, SwaggerDocument>(); 5 6 private readonly ISwaggerProvider _swaggerProvider; 7 8 public CachingSwaggerProvider(ISwaggerProvider swaggerProvider) 9 { 10 _swaggerProvider = swaggerProvider; 11 } 12 13 public SwaggerDocument GetSwagger(string rootUrl, string apiVersion) 14 { 15 var cacheKey = string.Format("{0}_{1}", rootUrl, apiVersion); 16 SwaggerDocument srcDoc = null; 17 //只讀取一次 18 if (!_cache.TryGetValue(cacheKey, out srcDoc)) 19 { 20 srcDoc = _swaggerProvider.GetSwagger(rootUrl, apiVersion); 21 22 srcDoc.vendorExtensions = new Dictionary<string, object> { { "ControllerDesc", GetControllerDesc() } }; 23 _cache.TryAdd(cacheKey, srcDoc); 24 } 25 return srcDoc; 26 } 27 28 /// <summary> 29 /// 從API文檔中讀取控制器描述 30 /// </summary> 31 /// <returns>所有控制器描述</returns> 32 public static ConcurrentDictionary<string, string> GetControllerDesc() 33 { 34 string xmlpath = string.Format("{0}/bin/Swagger.Mvc.xml", System.AppDomain.CurrentDomain.BaseDirectory); 35 ConcurrentDictionary<string, string> controllerDescDict = new ConcurrentDictionary<string, string>(); 36 if (File.Exists(xmlpath)) 37 { 38 XmlDocument xmldoc = new XmlDocument(); 39 xmldoc.Load(xmlpath); 40 string type = string.Empty, path = string.Empty, controllerName = string.Empty; 41 42 string[] arrPath; 43 int length = -1, cCount = "Controller".Length; 44 XmlNode summaryNode = null; 45 foreach (XmlNode node in xmldoc.SelectNodes("//member")) 46 { 47 type = node.Attributes["name"].Value; 48 if (type.StartsWith("T:")) 49 { 50 //控制器 51 arrPath = type.Split('.'); 52 length = arrPath.Length; 53 controllerName = arrPath[length - 1]; 54 if (controllerName.EndsWith("Controller")) 55 { 56 //獲取控制器註釋 57 summaryNode = node.SelectSingleNode("summary"); 58 string key = controllerName.Remove(controllerName.Length - cCount, cCount); 59 if (summaryNode != null && !string.IsNullOrEmpty(summaryNode.InnerText) && !controllerDescDict.ContainsKey(key)) 60 { 61 controllerDescDict.TryAdd(key, summaryNode.InnerText.Trim()); 62 } 63 } 64 } 65 } 66 } 67 return controllerDescDict; 68 } 69 70 71 }
在SwaggerConfig.cs 類 中放開註釋代碼:
c.CustomProvider((defaultProvider) => new CachingSwaggerProvider(defaultProvider));
再次運行程式後,現在變成中的了。
備註內容換行,在相應備註後邊加 <br></br>即可出現換行,換行標簽要成對出現,否則會報錯
最後運行效果如下:
總結:
最後有個問題,就是項目名稱中間不能用點來分割,比如: Swagger.Mvc 這樣就不行,這樣的名字,上邊漢化時會找不到路徑。所以需要把中間的點去掉,坑啊!