asp.net core中使用Swashbuckle.AspNetCore生成接口文檔
Swashbuckle.AspNetCore:swagger的asp.net core實現,本文使用版本為v1.1.0
項目地址:https://github.com/domaindrivendev/Swashbuckle.AspNetCore
仔細看了下readme,發現在百度找半天的東西其實readme里面就有...
開局一張圖,然后開始編,一些基本的asp.net core東西就不再贅述,本文只對Swashbuckle.AspNetCore的幾個使用要點進行描述。

如上圖所示,包含功能如下(完整示例見文末)
- 基礎使用,添加controler的說明(
IDocumentFilter) - 漢化操作按鈕
- 添加通用參數(header)-實現
IOperationFilter - 多版本控制(暫時見demo)
- 使用JWT的簡單接口驗證(暫時見demo)
構建一個webapi項目並使用swagger
- 新建asp.net core webapi項目
dotnet new webapi - 安裝nuget包:
Swashbuckle.AspNetCore,本文使用版本1.1.0,.net core版本2.0+ - 編輯解決方案添加(或者在vs中項目屬性->生成->勾選生成xml文檔文件)如下配置片段
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> <DocumentationFile>bin\Debug\netcoreapp2.0\項目名稱.xml</DocumentationFile> </PropertyGroup>
- 使用Swagger並注入漢化腳本
c.SwaggerDoc配置接口描述信息c.OperationFilter可通過IOperationFilter接口去添加一些公共的參數c.DocumentFilter通過IDocumentFilter接口去生成控制器的標簽(描述)
注:ConfigureServices的方法返回值修改了,為了能夠正常的使用ServiceLocator獲取服務
private const string _Project_Name = "AspNetCoreSwaggerDemo";//nameof(AspNetCoreSwaggerDemo); public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); services.AddSingleton(new ApiTokenConfig("A3FFB16D-D2C0-4F25-BACE-1B9E5AB614A6")); services.AddScoped<IApiTokenService, ApiTokenService>(); services.AddSwaggerGen(c => { typeof(ApiVersions).GetEnumNames().ToList().ForEach(version => { c.SwaggerDoc(version, new Swashbuckle.AspNetCore.Swagger.Info { Version = version, Title = $"{_Project_Name} 接口文檔", Description = $"{_Project_Name} HTTP API " + version, TermsOfService = "None" }); }); var basePath = Microsoft.Extensions.PlatformAbstractions.PlatformServices.Default.Application.ApplicationBasePath; var xmlPath = System.IO.Path.Combine(basePath, $"{_Project_Name}.xml"); c.IncludeXmlComments(xmlPath); //添加自定義參數,可通過一些特性標記去判斷是否添加 c.OperationFilter<AssignOperationVendorExtensions>(); //添加對控制器的標簽(描述) c.DocumentFilter<ApplyTagDescriptions>(); }); services.AddMvc(); return services.BuildServiceProvider(); }
使用
InjectOnCompleteJavaScript注入漢化js腳本即可
注:我在這個漢化腳本中添加了保存和讀取賦值token/版本的js代碼ApiVersions為枚舉,配置api版本,以期通過CustomRoute特性標記解決歷史api問題。
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseSwagger(); app.UseSwaggerUI(c => { //ApiVersions為自定義的版本枚舉 typeof(ApiVersions) .GetEnumNames() .OrderByDescending(e => e) .ToList() .ForEach(version => { //版本控制 c.SwaggerEndpoint($"/swagger/{version}/swagger.json", $"{_Project_Name} {version}"); }); //注入漢化腳本 c.InjectOnCompleteJavaScript($"/swagger_translator.js"); }); //通過ServiceLocator.Resolve<Service接口>()獲取注入的服務 ServiceLocator.Configure(app.ApplicationServices); app.UseStaticFiles(); app.UseMvc(); }
實現 IDocumentFilter 及 IOperationFilter
通過
IOperationFilter接口可以添加一些公共的參數,添加參數到header或者上傳圖片等
通過IDocumentFilter接口可以生成控制器的標簽(描述)
調用方式分別為:c.OperationFilter<AssignOperationVendorExtensions>();c.DocumentFilter<ApplyTagDescriptions>();
//添加標簽 public class ApplyTagDescriptions : IDocumentFilter { public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context) { swaggerDoc.Tags = new List<Tag> { //添加對應的控制器描述 這個是好不容易在issues里面翻到的 new Tag { Name = "Account", Description = "登錄相關接口" }, new Tag { Name = "UserCenter", Description = "用戶中心接} }; } }
//添加通用參數,若in='header'則添加到header中,默認query參數 public class AssignOperationVendorExtensions : IOperationFilter { public void Apply(Operation operation, OperationFilterContext context) { operation.Parameters = operation.Parameters ?? new List<IParameter>(); //MemberAuthorizeAttribute 自定義的身份驗證特性標記 var isAuthor = operation != null && context != null && context.ApiDescription.ControllerAttributes().Any(e => e.GetType() == typeof(MemberAuthorizeAttribute)) || context.ApiDescription.ActionAttributes().Any(e => e.GetType() == typeof(MemberAuthorizeAttribute)); if (isAuthor) { //in query header operation.Parameters.Add(new NonBodyParameter() { Name = "x-token", In = "header", //query formData .. Description = "身份驗證票據", Required = false, Type = "string" }); } } }
配置完成后,給Controler,Action添加上注釋和請求類型就可以訪問/swagger查看你的api文檔了~
注:
- action方法或者控制器(或者繼承的)必須有一個包含
[Route]特性標記 - action方法必須添加請求類型
[HttpGet]/[HttpPost]/..
如何自動將token保存並賦值
使用js生成了文本框到
.authorize-wrapper,將值保存到了本地存儲中,然后會根據接口版本將版本號參數進行復制
$(function () { //漢化 window.SwaggerTranslator.translate(); /***************下面是添加的token相關代碼*******************/ window.saveToken=function() { var test_token = $("#customtoken").val(); localStorage.setItem("test_x_token", $("#customtoken").val()); $("input[name='X-Token']").val(test_token) } //token保存 var test_token = localStorage.getItem("test_x_token")||""; $(".authorize-wrapper").append("X-Token:<input type='text' id='customtoken' value='" + test_token +"' style='width:50%' /> <button onClick='saveToken()'>保存</button>") $("input[name='X-Token']").val(test_token) $("input[name='X-Version']").val(swaggerUi.api.info.version) });
如何忽略一個接口
為Controller或者Action方法上添加特性標記[ApiExplorerSettings(IgnoreApi =true)]即可
下一篇:Swashbuckle.AspNetCore3.0的二次封裝與使用
文章完整示例
注:Demo 未修改默認啟動路徑,故應使用 /swagger/ 訪問文檔:,也可自行修改 /Properties/launchSettings.json 配置默認路徑
作者:易墨
個人小站:http://www.yimo.link
純靜態工具站點:http://tools.yimo.link/
說明:歡迎拍磚,不足之處還望園友們指出;
迷茫大概是因為想的太多做的太少。
