先看Startup.cs里:
public void ConfigureServices(IServiceCollection services) { services.AddTransient<IConfigureOptions<SwaggerGenOptions>, ConfigureSwaggerOptions>(); services.AddSwaggerGen(options => options.OperationFilter<SwaggerDefaultValues>()); services.AddControllers(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseSwagger(); app.UseSwaggerUI(option => { foreach (var description in provider.ApiVersionDescriptions) { c.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json", description.GroupName.ToUpperInvariant()); } }); }这里加了两个类,第一个ConfigureSwaggerOptions:
internal class ConfigureSwaggerOptions : IConfigureOptions<SwaggerGenOptions> { private readonly IApiVersionDescriptionProvider _provider; public ConfigureSwaggerOptions(IApiVersionDescriptionProvider provider) => _provider = provider; public void Configure(SwaggerGenOptions options) { foreach (var description in _provider.ApiVersionDescriptions) { options.SwaggerDoc(description.GroupName, CreateInfoForApiVersion(description)); } } private OpenApiInfo CreateInfoForApiVersion(ApiVersionDescription description) { var info = new OpenApiInfo() { Title = "Demo API", Version = description.ApiVersion.ToString(), }; if (description.IsDeprecated) { info.Description += " 方法被弃用."; } return info; } }第二个SwaggerDefaultValues:
internal class SwaggerDefaultValues : IOperationFilter { public void Apply(OpenApiOperation operation, OperationFilterContext context) { var apiDescription = context.ApiDescription; operation.Deprecated |= apiDescription.IsDeprecated(); if (operation.Parameters == null) return; foreach (var parameter in operation.Parameters) { var description = apiDescription.ParameterDescriptions.First(p => p.Name == parameter.Name); if (parameter.Description == null) { parameter.Description = description.ModelMetadata?.Description; } if (parameter.Schema.Default == null && description.DefaultValue != null) { parameter.Schema.Default = new OpenApiString(description.DefaultValue.ToString()); } parameter.Required |= description.IsRequired; } } }代码不一行行解释了,都是比较简单的。
运行,进入Swagger界面,右上角Select a definition,可以选择我们定义的版本号。
今天的配套代码已上传到Github,位置在:https://github.com/humornif/Demo-Code/tree/master/0035/demo
微信公众号:老王Plus