Web Api使用Swagger除錯介面
阿新 • • 發佈:2019-02-18
最近的專案都是前後端分離的,後端都是提供Api介面的。
有時除錯起來很不方便,給前端的wpi文件也需要經常變更很不方便。
如是網上搜了下,發現SwaggerUI還挺強大的,除錯介面也比較方便,在此記錄下:
1、引入Swashbuckle
第一個就是,我裝的版本是5.6.0
設定xml檔案輸出路徑:
在 App_Start 會生成 SwaggerConfig.cs,需要修改裡面的內容:
public static void Register() { var thisAssembly = typeof(SwaggerConfig).Assembly; GlobalConfiguration.Configuration .EnableSwagger(c => { c.SingleApiVersion("v1", "WebApiSwagger"); c.IncludeXmlComments(GetXmlCommentsPath()); //token認證 //c.OperationFilter<HttpHeaderFilter>(); }) .EnableSwaggerUi(c => { //漢化 //c.InjectJavaScript(Assembly.GetExecutingAssembly(), "WebApiSwagger.SwaggerUi.scripts.swagger.js"); }); } private static string GetXmlCommentsPath() { return System.String.Format(@"{0}/App_Data/WebApiSwagger.xml", System.AppDomain.CurrentDomain.BaseDirectory); }
修改訪問的起始頁:
偷個懶,只需在home控制器裡做個跳轉
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Title = "Home Page";
Response.Redirect("/swagger/ui/index/");
return View();
}
}
在App_Start 中新增一個類 IOperationFilter.cs :
using Swashbuckle.Swagger; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Http.Description; using System.Web.Http.Filters; namespace WebApiSwagger.App_Start { /// <summary> /// /// </summary> public class HttpHeaderFilter : IOperationFilter { /// <summary> /// /// </summary> /// <param name="operation"></param> /// <param name="schemaRegistry"></param> /// <param name="apiDescription"></param> public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription) { if (operation.parameters == null) operation.parameters = new List<Parameter>(); var filterPipeline = apiDescription.ActionDescriptor.GetFilterPipeline(); //判斷是否新增許可權過濾器 var isAuthorized = filterPipeline.Select(filterInfo => filterInfo.Instance).Any(filter => filter is IAuthorizationFilter); //判斷是否允許匿名方法 var allowAnonymous = apiDescription.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any(); if (isAuthorized && !allowAnonymous) { operation.parameters.Add(new Parameter { name = "Authorization", @in = "header", description = "Token", required = false, type = "string" }); } } } }
修改:
public static void Register()
{
var thisAssembly = typeof(SwaggerConfig).Assembly;
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.SingleApiVersion("v1", "WebApiSwagger");
c.IncludeXmlComments(GetXmlCommentsPath());
c.OperationFilter<HttpHeaderFilter>();
})
.EnableSwaggerUi(c=> {
c.InjectJavaScript(Assembly.GetExecutingAssembly(), "WebApiSwagger.SwaggerUi.scripts.swagger.js");
//c.InjectStylesheet();
});
}
漢化:
js內容:
'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;
}
};
/* 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();
});
效果圖:
自動獲取token,在swagger.js新增:
$(function () {
window.SwaggerTranslator.translate();
//自動獲取Token
$.ajax({
type: "POST",
url: "/token",
data: "grant_type=password&username=admin&password=admin",
success: function (res) {
var token = res['access_token'];
$("input[name='Authorization']").val('Bearer ' + token);
},
dataType: 'Json',
});
});