From f1ed45af96c7c92fea699a4e17e44cc1cc411bc4 Mon Sep 17 00:00:00 2001 From: Polianin Nikita Date: Fri, 26 Jan 2024 19:33:25 +0300 Subject: [PATCH] feat: add API versioning --- Endpoint/Program.cs | 39 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 37 insertions(+), 2 deletions(-) diff --git a/Endpoint/Program.cs b/Endpoint/Program.cs index a9156f9..334eccc 100644 --- a/Endpoint/Program.cs +++ b/Endpoint/Program.cs @@ -41,8 +41,33 @@ public class Program policy.AllowAnyOrigin(); }); }); + + builder.Services.AddApiVersioning(options => + { + options.DefaultApiVersion = new ApiVersion(1, 0); + options.AssumeDefaultVersionWhenUnspecified = true; + options.ReportApiVersions = true; + options.ApiVersionReader = new UrlSegmentApiVersionReader(); + }); + + builder.Services.AddVersionedApiExplorer(options => + { + options.GroupNameFormat = "'v'VVV"; + options.SubstituteApiVersionInUrl = true; + }); + builder.Services.AddEndpointsApiExplorer(); - builder.Services.AddSwaggerGen(); + + builder.Services.AddSwaggerGen(options => + { + options.OperationFilter(); + var basePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory); + + var xmlPath = Path.Combine(basePath, "docs.xml"); + options.IncludeXmlComments(xmlPath); + }); + + builder.Services.AddTransient, ConfigureSwaggerOptions>(); var app = builder.Build(); @@ -50,7 +75,17 @@ public class Program if (app.Environment.IsDevelopment()) { app.UseSwagger(); - app.UseSwaggerUI(); + app.UseSwaggerUI(options => + { + var provider = app.Services.GetService(); + + foreach (var description in provider.ApiVersionDescriptions) + { + var url = $"/swagger/{description.GroupName}/swagger.json"; + var name = description.GroupName.ToUpperInvariant(); + options.SwaggerEndpoint(url, name); + } + }); } app.UseHttpsRedirection();