namespace ApiVersioningSample { using System; using System.Linq;
using Microsoft.AspNetCore.Mvc.ApiExplorer; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
/// <summary> /// Configures the Swagger generation options. /// </summary> /// <remarks> /// <para> /// This allows API versioning to define a Swagger document per API version after the /// <see cref="IApiVersionDescriptionProvider" /> service has been resolved from the service container. /// </para> /// <para>Taken from https://github.com/microsoft/aspnet-api-versioning.</para> /// </remarks> public class ConfigureSwaggerOptions : IConfigureOptions<SwaggerGenOptions> { #region member vars
/// <summary> /// Initializes a new instance of the <see cref="ConfigureSwaggerOptions" /> class. /// </summary> /// <param name="provider"> /// The <see cref="IApiVersionDescriptionProvider">provider</see> used to generate Swagger /// documents. /// </param> public ConfigureSwaggerOptions(IApiVersionDescriptionProvider provider) { _provider = provider; }
#endregion
#region explicit interfaces
/// <inheritdoc /> public void Configure(SwaggerGenOptions options) { // add a swagger document for each discovered API version // note: you might choose to skip or document deprecated API versions differently foreach (var description in _provider.ApiVersionDescriptions) { options.SwaggerDoc(description.GroupName, CreateInfoForApiVersion(description)); } }
#endregion
#region methods
/// <summary> /// Internal implementation for building the Swagger basic config. /// </summary> /// <param name="description">The description object containing the.</param> /// <returns>The generated Open API info.</returns> private static OpenApiInfo CreateInfoForApiVersion(ApiVersionDescription description) { var info = new OpenApiInfo { Title = "Sample API", Version = description.ApiVersion.ToString(), Description = @"<p>Sample API with versioning including Swagger.</p><p>Partly taken from <a href=""https://github.com/microsoft/aspnet-api-versioning"">this repository</a>.</p>", Contact = new OpenApiContact { Name = "Yu Hsiang", } }; if (description.IsDeprecated) { info.Description += @"<p><strong><span style=""color:white;background-color:red"">VERSION IS DEPRECATED</span></strong></p>"; } return info; }
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using TodoAPI.Models; using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; using Microsoft.Extensions.Options; using ApiVersioningSample; using Microsoft.AspNetCore.Mvc.ApiExplorer;
namespace TodoAPI { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; }
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); // 資料庫配置 var connection = @"Server=.\SQLExpress;Database=TodoDB;Trusted_Connection=True;ConnectRetryCount=0"; services.AddDbContext<TodoDBContext>(options => options.UseSqlServer(connection));
// 啟用API版控功能 services.AddApiVersioning( options => { // reporting api versions will return the headers "api-supported-versions" and "api-deprecated-versions" options.ReportApiVersions = true; });
// swagger 配置 services.AddVersionedApiExplorer( options => { // add the versioned api explorer, which also adds IApiVersionDescriptionProvider service // note: the specified format code will format the version as "'v'major[.minor][-status]" options.GroupNameFormat = "'v'VVV"; // note: this option is only necessary when versioning by url segment. the SubstitutionFormat // can also be used to control the format of the API version in route templates options.SubstituteApiVersionInUrl = true; }); services.AddTransient<IConfigureOptions<SwaggerGenOptions>, ConfigureSwaggerOptions>(); services.AddSwaggerGen();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IApiVersionDescriptionProvider provider) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); }
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization(); // swagger 配置 app.UseSwagger(); app.UseSwaggerUI( options => { // build a swagger endpoint for each discovered API version foreach (var description in provider.ApiVersionDescriptions) { options.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json", description.GroupName.ToUpperInvariant()); } });