一個使用 ASP.NET Core 構建的 API 的 Swagger 工具。直接從您的路由,控制器和模型生成漂亮的 API 文檔,包括用於探索和測試操做的 UI。
項目主頁:https://github.com/domaindrivendev/Swashbuckle.AspNetCore
項目官方示例:https://github.com/domaindrivendev/Swashbuckle.AspNetCore/tree/master/test/WebSitescss
以前寫過一篇Swashbuckle.AspNetCore-v1.10 的使用,如今 Swashbuckle.AspNetCore
已經升級到 3.0 了,正好開新坑(博客重構)從新封裝了下,將全部相關的一些東西抽取到單獨的類庫中,儘量的避免和項目耦合,使其可以在其餘項目也可以快速使用。html
待博客重構完成再將完整代碼開源,參考下面步驟可自行封裝
git
我引用的版本以下github
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.1.1" /> <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.1.1" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="3.0.0" />
public class CustsomSwaggerOptions { /// <summary> /// 項目名稱 /// </summary> public string ProjectName { get; set; } = "My API"; /// <summary> /// 接口文檔顯示版本 /// </summary> public string[] ApiVersions { get; set; } /// <summary> /// 接口文檔訪問路由前綴 /// </summary> public string RoutePrefix { get; set; } = "swagger"; /// <summary> /// 使用自定義首頁 /// </summary> public bool UseCustomIndex { get; set; } /// <summary> /// UseSwagger Hook /// </summary> public Action<SwaggerOptions> UseSwaggerAction { get; set; } /// <summary> /// UseSwaggerUI Hook /// </summary> public Action<SwaggerUIOptions> UseSwaggerUIAction { get; set; } /// <summary> /// AddSwaggerGen Hook /// </summary> public Action<SwaggerGenOptions> AddSwaggerGenAction { get; set; } }
public class SwaggerDefaultValueFilter : IOperationFilter { public void Apply(Swashbuckle.AspNetCore.Swagger.Operation operation, OperationFilterContext context) { // REF: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/412 // REF: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/pull/413 foreach (var parameter in operation.Parameters.OfType<NonBodyParameter>()) { var description = context.ApiDescription.ParameterDescriptions.FirstOrDefault(p => p.Name == parameter.Name); if (description == null) return; if (parameter.Description == null) { parameter.Description = description.ModelMetadata.Description; } if (description.RouteInfo != null) { parameter.Required |= !description.RouteInfo.IsOptional; if (parameter.Default == null) parameter.Default = description.RouteInfo.DefaultValue; } } }
public static class CustomSwaggerServiceCollectionExtensions { public static IServiceCollection AddCustomSwagger(this IServiceCollection services) { return AddCustomSwagger(services, new CustsomSwaggerOptions()); } public static IServiceCollection AddCustomSwagger(this IServiceCollection services, CustsomSwaggerOptions options) { services.AddSwaggerGen(c => { if (options.ApiVersions == null) return; foreach (var version in options.ApiVersions) { c.SwaggerDoc(version, new Info { Title = options.ProjectName, Version = version }); } c.OperationFilter<SwaggerDefaultValueFilter>(); options.AddSwaggerGenAction?.Invoke(c); }); return services; } }
public static class SwaggerBuilderExtensions { public static IApplicationBuilder UseCustomSwagger(this IApplicationBuilder app) { return UseCustomSwagger(app, new CustsomSwaggerOptions()); } public static IApplicationBuilder UseCustomSwagger(this IApplicationBuilder app, CustsomSwaggerOptions options) { app.UseSwagger(opt => { if (options.UseSwaggerAction == null) return; options.UseSwaggerAction(opt); }); app.UseSwaggerUI(c => { if (options.ApiVersions == null) return; c.RoutePrefix = options.RoutePrefix; c.DocumentTitle = options.ProjectName; if (options.UseCustomIndex) { c.UseCustomSwaggerIndex(); } foreach (var item in options.ApiVersions) { c.SwaggerEndpoint($"/swagger/{item}/swagger.json", $"{item}"); } options.UseSwaggerUIAction?.Invoke(c); }); return app; } /// <summary> /// 使用自定義首頁 /// </summary> /// <returns></returns> public static void UseCustomSwaggerIndex(this SwaggerUIOptions c) { var currentAssembly = typeof(CustsomSwaggerOptions).GetTypeInfo().Assembly; c.IndexStream = () => currentAssembly.GetManifestResourceStream($"{currentAssembly.GetName().Name}.index.html"); } }
private CustsomSwaggerOptions CURRENT_SWAGGER_OPTIONS = new CustsomSwaggerOptions() { ProjectName = "墨玄涯博客接口", ApiVersions = new string[] { "v1", "v2" },//要顯示的版本 UseCustomIndex = true, RoutePrefix = "swagger", AddSwaggerGenAction = c => { var filePath = System.IO.Path.Combine(System.AppContext.BaseDirectory, typeof(Program).GetTypeInfo().Assembly.GetName().Name + ".xml"); c.IncludeXmlComments(filePath, true); }, UseSwaggerAction = c => { }, UseSwaggerUIAction = c => { } };
添加對新建類庫的引用,並在 webapi 項目中啓用版本管理須要爲輸出項目添加 Nuget 包:Microsoft.AspNetCore.Mvc.Versioning
,Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer
(若是須要版本管理則添加)web
我引用的版本以下json
<PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning" Version="2.3.0" /> <PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer" Version="2.2.0" />
Startup.cs 代碼api
public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); //版本控制 services.AddMvcCore().AddVersionedApiExplorer(o => o.GroupNameFormat = "'v'VVV"); services.AddApiVersioning(option => { // allow a client to call you without specifying an api version // since we haven't configured it otherwise, the assumed api version will be 1.0 option.AssumeDefaultVersionWhenUnspecified = true; option.ReportApiVersions = false; }); //custom swagger services.AddCustomSwagger(CURRENT_SWAGGER_OPTIONS); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApiVersionDescriptionProvider provider) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } //custom swagger //自動檢測存在的版本 // CURRENT_SWAGGER_OPTIONS.ApiVersions = provider.ApiVersionDescriptions.Select(s => s.GroupName).ToArray(); app.UseCustomSwagger(CURRENT_SWAGGER_OPTIONS); app.UseMvc(); }
new CustsomSwaggerOptions(){ AddSwaggerGenAction = c => { var filePath = System.IO.Path.Combine(System.AppContext.BaseDirectory, typeof(Program).GetTypeInfo().Assembly.GetName().Name + ".xml"); //controller及action註釋 c.IncludeXmlComments(filePath, true); } }
固然還須要生成xml,編輯解決方案添加(或者在vs中項目屬性->生成->勾選生成xml文檔文件)以下配置片斷app
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'"> <DocumentationFile>.\項目名稱.xml</DocumentationFile> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> <DocumentationFile>.\項目名稱.xml</DocumentationFile> </PropertyGroup>
目前.net core2.1我這會將此 xml 生成到項目目錄,故可能須要將其加入.gitignore中。dom
添加 Nuget 包:Microsoft.AspNetCore.Mvc.Versioning
,Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer
並在 ConfigureServices 中設置ide
//版本控制 services.AddMvcCore().AddVersionedApiExplorer(o => o.GroupNameFormat = "'v'VVV"); services.AddApiVersioning(option => { // allow a client to call you without specifying an api version // since we haven't configured it otherwise, the assumed api version will be 1.0 option.AssumeDefaultVersionWhenUnspecified = true; option.ReportApiVersions = false; });
controller 使用
/// <summary> /// 測試接口 /// </summary> [ApiVersion("1.0")] [Route("api/v{api-version:apiVersion}/test")] [ApiController] public class TestController : ControllerBase { }
將 index.html 修改成內嵌資源就可使用GetManifestResourceStream
獲取文件流,使用此 html,能夠本身使用var configObject = JSON.parse('%(ConfigObject)');
獲取到 swagger 的配置信息,從而根據此信息去寫本身的主題便可。
/// <summary> /// 使用自定義首頁 /// </summary> /// <returns></returns> public static void UseCustomSwaggerIndex(this SwaggerUIOptions c) { var currentAssembly = typeof(CustsomSwaggerOptions).GetTypeInfo().Assembly; c.IndexStream = () => currentAssembly.GetManifestResourceStream($"{currentAssembly.GetName().Name}.index.html"); }
若想注入 css,js 則在 UseSwaggerUIAction 委託中調用對應的方法接口,官方文檔
另外,目前 swagger-ui 3.19.0 並不支持多語言,不過能夠根據須要使用 js 去修改一些東西
好比在 index.html 的 onload 事件中這樣去修改頭部信息
document.getElementsByTagName( 'span' )[0].innerText = document .getElementsByTagName('span')[0] .innerText.replace('swagger', '項目接口文檔') document.getElementsByTagName( 'span' )[1].innerText = document .getElementsByTagName('span')[1] .innerText.replace('Select a spec', '版本選擇')
在找漢化解決方案時追蹤到 Swashbuckle.AspNetCore3.0 主題時使用的swagger-ui 爲 3.19.0,從issues2488瞭解到目前不支持多語言,其餘的問題也能夠查看此倉庫
在使用過程當中遇到的問題,基本上 readme 和 issues 都有答案,遇到問題多多閱讀便可