ConfigureSwaggerOptions.cs

    0

    0

    This code uses the IConfigureOptions interface to configure the SwaggerGenOptions object. The Configure method sets the SwaggerGenOptions object's configuration values. The OpenApiInfo class is used to generate a description of the API. If the API version is deprecated, the Description property will include the message "This API version has been deprecated.

    using Microsoft.AspNetCore.Mvc.ApiExplorer;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Options;
    using Microsoft.OpenApi.Models;
    using Swashbuckle.AspNetCore.SwaggerGen;
    
    
    
    namespace SampleWebApiAspNetCore
    {
      public class ConfigureSwaggerOptions : IConfigureOptions<SwaggerGenOptions>
      {
        readonly IApiVersionDescriptionProvider provider;
    
        public ConfigureSwaggerOptions(IApiVersionDescriptionProvider provider) => this.provider = provider;
    
        public void Configure(SwaggerGenOptions options)
        {
          foreach (var description in provider.ApiVersionDescriptions)
          {
            options.SwaggerDoc(description.GroupName, CreateInfoForApiVersion(description));
          }
        }
    
        static OpenApiInfo CreateInfoForApiVersion(ApiVersionDescription description)
        {
          var info = new OpenApiInfo()
          {
            Title = "Sample API",
            Version = description.ApiVersion.ToString(),
            Description = "A sample application with Swagger, Swashbuckle, and API versioning.",
          };
    
          if (description.IsDeprecated)
          {
            info.Description += " This API version has been deprecated.";
          }
    
          return info;
        }
      }
    }
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Explore
    • Cookbooks
    • Playground
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.