using Asp.Versioning.ApiExplorer; using Microsoft.Extensions.Options; using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; using Swashbuckle.AspNetCore.SwaggerUI; namespace Core.Cerberos.Service.API.Extensions { public static class SwaggerExtensions { public static void AddSwagger(this IServiceCollection services, IConfiguration configuration) { services.AddEndpointsApiExplorer(); AddSwaggerGen(services, configuration); services.AddTransient, ConfigureSwaggerOptions>(); } /// /// Configures Swagger generation with OAuth2 security and XML comments. /// /// The to add the services to. /// The containing Swagger and OAuth2 configuration settings. public static void AddSwaggerGen(this IServiceCollection services, IConfiguration configuration) { services.AddSwaggerGen(c => { c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { Description = "JWT Authorization header using the Bearer scheme", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.Http, Scheme = "bearer", BearerFormat = "JWT" }); c.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" } }, Array.Empty() } }); }); } public static void ConfigureSwagger(this WebApplication app) { //Swagger Stuff Goes Here app.UseSwagger(); app.UseSwaggerUI(options => { foreach (var version in app.DescribeApiVersions().Select(version => version.GroupName)) options.SwaggerEndpoint($"/swagger/{version}/swagger.json", version); options.DisplayRequestDuration(); options.EnableTryItOutByDefault(); options.DocExpansion(DocExpansion.None); }); // app.MapGet("/", () => Results.Redirect("/swagger/index.html")).WithTags(string.Empty); } public static IServiceCollection AddVersioning(this IServiceCollection services) { services.AddApiVersioning(options => options.ReportApiVersions = true) .AddApiExplorer(options => { options.GroupNameFormat = "'v'VVV"; options.SubstituteApiVersionInUrl = true; }); return services; } } public class ConfigureSwaggerOptions(IApiVersionDescriptionProvider provider) : IConfigureOptions { private readonly IApiVersionDescriptionProvider _provider = provider; public void Configure(SwaggerGenOptions options) { foreach (var description in _provider.ApiVersionDescriptions) options.SwaggerDoc(description.GroupName, new() { Title = AppDomain.CurrentDomain.FriendlyName, Version = description.ApiVersion.ToString() }); options.CustomSchemaIds(type => type.ToString().Replace("+", ".")); } } }