ASP.NET WebAPI使用Swagger生成測試文檔

来源:https://www.cnblogs.com/yyfh/archive/2017/12/25/8107866.html
-Advertisement-
Play Games

ASP.NET WebAPI使用Swagger生成測試文檔 SwaggerUI是一個簡單的Restful API測試和文檔工具。簡單、漂亮、易用(官方demo)。通過讀取JSON配置顯示API .項目本身僅僅也只依賴一些html,css,js靜態文件.你可以幾乎放在任何Web容器上使用 搗鼓了好久最 ...


ASP.NET WebAPI使用Swagger生成測試文檔

SwaggerUI是一個簡單的Restful API測試和文檔工具。簡單、漂亮、易用(官方demo)。通過讀取JSON配置顯示API .項目本身僅僅也只依賴一些html,css,js靜態文件.你可以幾乎放在任何Web容器上使用

搗鼓了好久最終效果如下

1、API控制器和action描述

2、測試介面

使用swagger

1.創建webapi項目解決方案

2.引用swagger nuget包

swashbuckle和swagger.NET

刪除多餘的SwaggerUI文件夾和配置類SwaggerNet

3、添加介面註釋

接下來可以訪問http://xxxx/swagger 這樣並看不到註釋

項目屬性->勾選生成xml文檔文件

修改SwaggerConfig文件

c.IncludeXmlComments(string.Format(@"{0}\App_Data\Api.xml",AppDomain.CurrentDomain.BaseDirectory));

漢化

1.SwaggerConfig

js文件需要嵌入到dll

/// <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();

 

2.控制器描述和介面文檔緩存

public class CachingSwaggerProvider : ISwaggerProvider
{
private static ConcurrentDictionary<string, SwaggerDocument> _cache =
new ConcurrentDictionary<string, SwaggerDocument>();

private readonly ISwaggerProvider _swaggerProvider;

public CachingSwaggerProvider(ISwaggerProvider swaggerProvider)
{
_swaggerProvider = swaggerProvider;
}

public SwaggerDocument GetSwagger(string rootUrl, string apiVersion)
{
var cacheKey = string.Format("{0}_{1}", rootUrl, apiVersion);
SwaggerDocument srcDoc = null;
//只讀取一次
if (!_cache.TryGetValue(cacheKey, out 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 static ConcurrentDictionary<string, string> GetControllerDesc()
{
string xmlpath = string.Format(@"{0}\App_Data\Api.xml", System.AppDomain.CurrentDomain.BaseDirectory);
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;
}
}

有什麼問題大家可以在下麵評論,本人技術不怎麼到位,寫的不好希望大家見諒。


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 1、示例代碼 (註:寫到vue單文件中了) 2、說明 (1)需要transition 標簽包裹。 (2)6個class狀態 (3)效果: ...
  • 本節流程如圖: 現在正式進入打包流程,起步方法為run: 為什麼不介紹compiler對象?因為構造函數中並沒有一個初始化的方法,只是普通的變數聲明,沒啥好講的。 在run方法中,首先是調用了tapable的applyPluginsAsync執行了before-run事件流,該事件流的定義地點如下: ...
  • 例如: !function(){alert('ok')}(); 常見格式:(function() { /* code */ })(); //也等同於此 匿名函數 解釋:包圍函數(function(){})的第一對括弧向腳本返回未命名的函數,隨後一對空括弧立即執行返回的未命名函數,括弧內為匿名函數的參 ...
  • 需求說明:簡單演示ajax提交fromData類型數據。 代碼說明:ajax在傳輸數據的時候基本格式大都是固定的,只需要修改傳輸類型即可。下麵介紹基本的參數提交。 步驟一:建立html或者jsp頁面,引入jquery-3.2.1.min.js(其他版本亦可)。 步驟二:建立文件選擇輸入框,上傳按鈕並 ...
  • 閱讀目錄: 主機安裝 集群搭建 API 操作 API 說明和 etcdctl 命令說明 "etcd" 是 CoreOS 團隊發起的一個開源項目(Go 語言,其實很多這類項目都是 Go 語言實現的,只能說很強大),實現了 分散式鍵值存儲 和 服務發現 ,etcd 和 ZooKeeper/Consul ...
  • 原文地址:http://www.woshipm.com/pmd/160822.html+ 支付寶系統架構概況 典型處理預設 資金處理平臺 財務會計 支付清算 核算中心 交易 柔性事務 支付寶的開源分散式消息中間件–Metamorphosis(MetaQ) Metamorphosis (MetaQ) ... ...
  • 轉碼對於普通用戶來說不可見的,但卻是短視頻SDK的一個重要過程。 ...
  • 當前環境:Windows 7 64位 ps:本博客都是基於Windows,Linux請繞行~ 1.下載Python 安裝包 官網地址 選擇適合自己的安裝包,當前最高版本Python 3.X 2.下載適合自己的Ide,比如 VisualStudio、VS Code、WingIDE、Vim、Pychar ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...