1.使用Swashbuckle實現javascript
Swashbuckle 是.NET類庫,能夠將WebAPI全部開放的控制器方法生成對應SwaggerUI的JSON配置。再經過SwaggerUI 顯示出來。類庫中已經包含SwaggerUI 。因此不須要額外安裝。html
2.快速開始。前提已有webapi項目java
查看webapi項目屬性,在【生成】選項卡中勾選X【ML文檔文件】。在編譯過程當中會生成一個註釋文件node
/// <summary> /// 自定義swagger的控制器描述 /// </summary> public class SwaggerControllerDescProvider : ISwaggerProvider { private readonly ISwaggerProvider _swaggerProvider; private readonly string _xml; /// /// /// /// /// xml文檔路徑 public SwaggerControllerDescProvider(ISwaggerProvider swaggerProvider, string xml) { _swaggerProvider = swaggerProvider; _xml = xml; } public SwaggerDocument GetSwagger(string rootUrl, string apiVersion) { SwaggerDocument srcDoc = null; srcDoc = _swaggerProvider.GetSwagger(rootUrl, apiVersion); srcDoc.vendorExtensions = new Dictionary<string, object> { { "ControllerDesc", GetControllerDesc() } }; return srcDoc; } /// /// 從API文檔中讀取控制器描述 /// /// 全部控制器描述 public ConcurrentDictionary<string, string> GetControllerDesc() { string xmlpath = _xml; ConcurrentDictionary<string, string> controllerDescDict = new ConcurrentDictionary<string, string>(); if (File.Exists(xmlpath)) { XmlDocument xmldoc = new XmlDocument(); xmldoc.Load(xmlpath); string type = string.Empty, path = string.Empty, controllerName = string.Empty; string[] arrPath; int length = -1, cCount = "Controller".Length; XmlNode summaryNode = null; foreach (XmlNode node in xmldoc.SelectNodes("//member")) { type = node.Attributes["name"].Value; if (type.StartsWith("T:")) { //控制器 arrPath = type.Split('.'); length = arrPath.Length; controllerName = arrPath[length - 1]; if (controllerName.EndsWith("Controller")) { //獲取控制器註釋 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; } }
'use strict'; /** * Translator for documentation pages. * * To enable translation you should include one of language-files in your index.html * after <script src='lang/translator.js' type='text/javascript'></script>. * For example - <script src='lang/ru.js' type='text/javascript'></script> * * If you wish to translate some new texsts you should do two things: * 1. Add a new phrase pair ("New Phrase": "New Translation") into your language file (for example lang/ru.js). It will be great if you add it in other language files too. * 2. Mark that text it templates this way <anyHtmlTag data-sw-translate>New Phrase</anyHtmlTag> or <anyHtmlTag data-sw-translate value='New Phrase'/>. * The main thing here is attribute data-sw-translate. Only inner html, title-attribute and value-attribute are going to translate. * */ 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'))); }); }, _tryTranslate: function (word) { return this._words[$.trim(word)] !== undefined ? this._words[$.trim(word)] : word; }, learn: function (wordsMap) { this._words = wordsMap; }, setControllerSummary: function () { $.ajax({ type: "get", async: true, url: $("#input_baseUrl").val(), dataType: "json", success: function (data) { //console.log(data) var toggleEndpointList = []; var summaryDict = data.ControllerDesc; var id, controllerName, strSummary; var s = $("#resources .resource"); $("#resources .resource").each(function (i, item) { id = $(item).attr("id"); if (id) { controllerName = id.substring(9, 11) + "_" + id.substring(13); strSummary = summaryDict[controllerName]; if (strSummary) { console.log($(item)) $(item).children(".heading").children("h2").children('a').text(strSummary); $(item).children(".heading").children(".options").prepend('<li class="controller-summary" title="' + strSummary + '">' + strSummary + '</li>'); toggleEndpointList.push($(item).attr('id')) } } }); for (var i = 0; i < document.getElementsByClassName('menuLiA').length; i++) { var menuLiA = document.getElementsByClassName('menuLiA'); menuLiA[i].setAttribute('href', '#' + toggleEndpointList[i]) } }, error: function (err) { alert(err); } }); }, }; /* 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 () { $("#logo").html("WebApi說明文檔"); window.SwaggerTranslator.translate(); window.SwaggerTranslator.setControllerSummary(); });