第一步:在nuget程序包管理中搜索“Swashbuckle”包,然后進(jìn)行安裝(注:如果是.net core api請(qǐng)安裝Sawshbuckle aspnetcore)。
第二步:打開項(xiàng)目App_Start文件夾,修改SwaggerConfig.cs配置文件
我這里僅僅是修改swagger文檔的標(biāo)題
第三步:創(chuàng)建主項(xiàng)目的xml注釋文檔:
右鍵項(xiàng)目→屬性→生成→選中下方的 "XML文檔文件" 然后保存
如果是其他類庫(kù)項(xiàng)目,比如實(shí)體類庫(kù),用于創(chuàng)建接口請(qǐng)求參數(shù)實(shí)體或返回參數(shù)實(shí)體項(xiàng)目,需要在swagger文檔中展示備注時(shí),可在啟動(dòng)項(xiàng)中添加配置:
c.IncludeXmlComments(XmlCommentsHelper.XmlCommentsPath);
c.IncludeXmlComments(XmlCommentsHelper.ModelXmlCommentsPath);
/// <summary>
/// 需要展示在swagger文檔中實(shí)體XML路徑
/// </summary>
public class XmlCommentsHelper
{
/// <summary>
/// XML注釋路徑
/// </summary>
public static string XmlCommentsPath
{
get
{
string path = string.Format("{0}/bin/MustWinLotteryWebApi.xml", System.AppDomain.CurrentDomain.BaseDirectory);
return path;
}
}
/// <summary>
/// 模型XML注釋路徑
/// </summary>
public static string ModelXmlCommentsPath
{
get
{
string path = string.Format("{0}/bin/MustWinLotteryWebApi.Model.xml", System.AppDomain.CurrentDomain.BaseDirectory);
return path;
}
}
}
完成以上操作后,可直接啟動(dòng)webapi項(xiàng)目,然后在接口地址后面輸入 /swagger ? (默認(rèn)是英文的,如果需要中文顯示 ?還需要做漢化處理)
以下是對(duì)swagger文檔進(jìn)行漢化處理方法:
第一步:在nuget程序包管理中搜索“Swagger.Net”包和“Swagger.Net.UI”,然后進(jìn)行安裝。
第二步:安裝完成后,注釋掉SwaggerNet類中的assembly
第三步:創(chuàng)建一個(gè)“SwaggerControllerDescProvider”類,用于對(duì)swagger文檔中的內(nèi)容進(jìn)行漢化處理。
/// <summary>
/// swagger顯示控制器的描述
/// </summary>
public class SwaggerControllerDescProvider : ISwaggerProvider
{
private readonly ISwaggerProvider _swaggerProvider;
private static ConcurrentDictionary<string, SwaggerDocument> _cache = new ConcurrentDictionary<string, SwaggerDocument>();
private readonly string _xml;
/// <summary>
///
/// </summary>
/// <param name="swaggerProvider"></param>
/// <param name="xml">xml文檔路徑</param>
public SwaggerControllerDescProvider(ISwaggerProvider swaggerProvider, string xml)
{
_swaggerProvider = swaggerProvider;
_xml = xml;
}
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 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("http://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;
}
}
第四步:在SwaggerUI文件夾中,創(chuàng)建一個(gè)swagger_lang.js的js,用于對(duì)swagger進(jìn)行漢化處理(注:這個(gè)文件必須添加,否則漢化將失?。?/p>
swagger_lang.js 文件中的js內(nèi)容如下:
/// <summary>
/// 中文轉(zhuǎn)換
/// </summary>
var SwaggerTranslator = (function () {
//定時(shí)執(zhí)行檢測(cè)是否轉(zhuǎn)換成中文,最多執(zhí)行500次 即500*50/1000=25s
var iexcute = 0,
//中文語(yǔ)言包
_words = {
"Warning: Deprecated": "警告:已過(guò)時(shí)",
"Implementation Notes": "實(shí)現(xiàn)備注",
"Response Class": "響應(yīng)類",
"Status": "狀態(tài)",
"Parameters": "參數(shù)",
"Parameter": "參數(shù)",
"Value": "值",
"Description": "描述",
"Parameter Type": "參數(shù)類型",
"Data Type": "數(shù)據(jù)類型",
"Response Messages": "響應(yīng)消息",
"HTTP Status Code": "HTTP狀態(tài)碼",
"Reason": "原因",
"Response Model": "響應(yīng)模型",
"Request URL": "請(qǐng)求URL",
"Response Body": "響應(yīng)體",
"Response Code": "響應(yīng)碼",
"Response Headers": "響應(yīng)頭",
"Hide Response": "隱藏響應(yīng)",
"Headers": "頭",
"Try it out!": "試一下!",
"Show/Hide": "顯示/隱藏",
"List Operations": "顯示操作",
"Expand Operations": "展開操作",
"Raw": "原始",
"can't parse JSON. Raw result": "無(wú)法解析JSON. 原始結(jié)果",
"Model Schema": "模型架構(gòu)",
"Model": "模型",
"apply": "應(yīng)用",
"Username": "用戶名",
"Password": "密碼",
"Terms of service": "服務(wù)條款",
"Created by": "創(chuàng)建者",
"See more at": "查看更多:",
"Contact the developer": "聯(lián)系開發(fā)者",
"api version": "api版本",
"Response Content Type": "響應(yīng)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.": "無(wú)法從服務(wù)器讀取??赡軟]有正確設(shè)置access-control-origin。",
"Please specify the protocol for": "請(qǐng)指定協(xié)議:",
"Can't read swagger JSON from": "無(wú)法讀取swagger JSON于",
"Finished Loading Resource Information. Rendering Swagger UI": "已加載資源信息。正在渲染Swagger UI",
"Unable to read api": "無(wú)法讀取api",
"from path": "從路徑",
"Click to set as parameter value": "點(diǎn)擊設(shè)置參數(shù)",
"server returned": "服務(wù)器返回"
},
//定時(shí)執(zhí)行轉(zhuǎn)換
_translator2Cn = function () {
if ($("#resources_container .resource").length > 0) {
_tryTranslate();
}
if ($("#explore").text() == "Explore" && iexcute < 500) {
iexcute++;
setTimeout(_translator2Cn, 50);
}
},
//設(shè)置控制器注釋
_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) {
var option = $(item).children(".heading").children(".options");
if ($(option).children(".controller-summary").length > 0) {
$(option).children(".controller-summary").remove();
}
$(option).prepend('<li class="controller-summary" title="' + strSummary + '">' + strSummary + '</li>');
}
}
});
}
});
},
//嘗試將英文轉(zhuǎn)換成中文
_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 () {
$("#logo").html("公司名稱").attr("href", "http://www.xx.com");
$('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>');
//設(shè)置控制器描述
_setControllerSummary();
_translator2Cn();
},
translate: function () {
this.Translator();
}
}
})();
//執(zhí)行轉(zhuǎn)換
SwaggerTranslator.Translator();
這里需要注意,新增的swagger_lang.js文件需要修改文件屬性,將文件生成操作修改為“嵌入的資源”。
第五步:將創(chuàng)建的swagger_lang.js在SwaggerConfig文件中進(jìn)行引用:
文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-726750.html
c.InjectJavaScript(thisAssembly, "MustWinLotteryWebApi.SwaggerUI.swagger_lang.js"); //引用中文包
以上就是我對(duì)“.net framework中webapi使用swagger進(jìn)行接口文檔展示”的實(shí)現(xiàn)方式及漢化方式的整理,希望對(duì)各位碼友有幫助。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-726750.html
到了這里,關(guān)于.net framework中webapi使用swagger進(jìn)行接口文檔展示的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!