關於 Swashbuckle.AspNetCore3.0
一個使用 ASP.NET Core 構建的 API 的 Swagger 工具。直接從您的路由,控制器和模型生成漂亮的 API 文檔,包括用於探索和測試操作的 UI。
項目主頁:https://github.com/domaindrivendev/Swashbuckle.AspNetCore
項目官方示例:https://github.com/domaindrivendev/Swashbuckle.AspNetCore/tree/master/test/WebSites
之前寫過一篇Swashbuckle.AspNetCore-v1.10 的使用,現在 Swashbuckle.AspNetCore
已經升級到 3.0 了,正好開新坑(博客重構)重新封裝了下,將所有相關的一些東西抽取到單獨的類庫中,盡可能的避免和項目耦合,使其能夠在其他項目也能夠快速使用。
運行示例
封裝代碼
Swagger封裝相關源碼:https://github.com/moxycoding/moxy.api.dotnet/tree/master/src/Core/Moxy.Swagger
參考下面步驟可自行封裝
1. 新建類庫並添加引用
我引用的版本如下
<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" />
2. 構建參數模型 CustsomSwaggerOptions.cs
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; }
}
3. 版本控制默認參數接口實現 SwaggerDefaultValueFilter.cs
因為版本不同,相關示例已失效,請按照官方文檔使用。僅供參考。
官方相關文檔:https://github.com/domaindrivendev/Swashbuckle.AspNetCore#operation-filters
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;
}
}
}
最新版本的 IOperationFilter接口實現示例
public void Apply(Microsoft.OpenApi.Models.OpenApiOperation operation, OperationFilterContext context)
{
}
4. CustomSwaggerServiceCollectionExtensions.cs
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;
}
}
5. SwaggerBuilderExtensions.cs
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");
}
}
6. 模型初始化
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 =>
{
}
};
7. 在 api 項目中使用
添加對新建類庫的引用,並在 webapi 項目中啟用版本管理需要為輸出項目添加 Nuget 包:Microsoft.AspNetCore.Mvc.Versioning
,Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer
(如果需要版本管理則添加)
我引用的版本如下
<PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning" Version="2.3.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer" Version="2.2.0" />
Startup.cs 代碼
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();
}
關鍵代碼拆解
action 方法的 xml 注釋
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文檔文件)如下配置片段
<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中。
版本控制
添加 Nuget 包:Microsoft.AspNetCore.Mvc.Versioning
,Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer
並在 ConfigureServices 中設置
//版本控制
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 都有答案,遇到問題多多閱讀即可