Swashbuckle.AspNetCore:swagger的asp.net core實現,本文使用版本爲v1.1.0
項目地址:https://github.com/domaindrivendev/Swashbuckle.AspNetCore
仔細看了下readme,發如今百度找半天的東西其實readme裏面就有...html
開局一張圖,而後開始編,一些基本的asp.net core東西就再也不贅述,本文只對Swashbuckle.AspNetCore
的幾個使用要點進行描述。git
如上圖所示,包含功能以下(完整示例見文末)github
IDocumentFilter
)IOperationFilter
dotnet new webapi
Swashbuckle.AspNetCore
,本文使用版本1.1.0,.net core版本2.0+<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> <DocumentationFile>bin\Debug\netcoreapp2.0\項目名稱.xml</DocumentationFile> </PropertyGroup>
c.SwaggerDoc
配置接口描述信息
c.OperationFilter
可經過IOperationFilter
接口去添加一些公共的參數
c.DocumentFilter
經過IDocumentFilter
接口去生成控制器的標籤(描述)
注:ConfigureServices
的方法返回值修改了,爲了可以正常的使用ServiceLocator
獲取服務web
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問題。json
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>();
api
//添加標籤 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文檔了~
注:app
[Route]
特性標記[HttpGet]/[HttpPost]/..
使用js生成了文本框到
.authorize-wrapper
,將值保存到了本地存儲中,而後會根據接口版本將版本號參數進行復制asp.net
$(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)]
便可dom
下一篇:Swashbuckle.AspNetCore3.0的二次封裝與使用ide
注:Demo 未修改默認啓動路徑,故應使用 /swagger/
訪問文檔:,也可自行修改 /Properties/launchSettings.json
配置默認路徑