Search code examples
asp.net-coreswaggerswashbuckle.aspnetcore

Swagger versioning is not working. It displays all endpoints, despite the selected API version


all!

I am using Swagger in ASP.NET Core 3.1 application.

I need to create an endpoint for the new version of API and with the same route as a previous version.

My controller is:


namespace Application.Controllers
{
    [ApiVersion("1")]
    [ApiVersion("2")]
    [ApiController]
    [Route("api/v{version:apiVersion}")]
    public class CustomController: ControllerBase
    {
        [HttpGet]
        [Route("result")]
        public IActionResult GetResult()
        {
            return Ok("v1")
        }

        [HttpGet]
        [MapToApiVersion("2")]
        [Route("result")]
        public IActionResult GetResult(int number)
        {
            return Ok("v2")
        }
    }
}

My configuration:

            services.AddApiVersioning(
                options =>
                {
                    options.ReportApiVersions = true;
                });

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc($"v1", new OpenApiInfo { Title = "api1", Version = $"v1" });

                c.SwaggerDoc($"v2", new OpenApiInfo { Title = "api2", Version = $"v2" });         
         

                c.OperationFilter<RemoveVersionParameterFilter>();
                c.DocumentFilter<ReplaceVersionWithExactValueInPathFilter>();
                c.EnableAnnotations();
            });
app.UseSwagger().UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint($"/swagger/v1/swagger.json", $"api1 v1");
                c.SwaggerEndpoint($"/swagger/v2/swagger.json", $"api2 v2");
            });

After loading I get an error: Fetch error undefined /swagger/v1/swagger.json But If I change the second route to the "resutlTwo", I can observe both endpoints in swagger, ignoring current version (api1 v1 or api2 v2)

How can I see only 1 endpoint per API version?


Solution

  • I just tested your case with this setup.You are missing UrlSegmentApiVersionReader.

    public class SwaggerOptions
    {
        public string Title { get; set; }
        public string JsonRoute { get; set; }
        public string Description { get; set; }
        public List<Version> Versions { get; set; }
    
        public class Version
        {
            public string Name { get; set; }
            public string UiEndpoint { get; set; }
        }
    }
    

    In Startup#ConfigureServices

            // Configure versions 
            services.AddApiVersioning(apiVersioningOptions =>
            {
                apiVersioningOptions.ReportApiVersions = true;
                apiVersioningOptions.ApiVersionReader = new UrlSegmentApiVersionReader();
            });
    
            // Register the Swagger generator, defining 1 or more Swagger documents
            services.AddSwaggerGen(swaggerGenOptions =>
            {
                var swaggerOptions = new SwaggerOptions();
                Configuration.GetSection("Swagger").Bind(swaggerOptions);
    
                foreach (var currentVersion in swaggerOptions.Versions)
                {
                    swaggerGenOptions.SwaggerDoc(currentVersion.Name, new OpenApiInfo
                    {
                        Title = swaggerOptions.Title,
                        Version = currentVersion.Name,
                        Description = swaggerOptions.Description
                    });
                }
    
                swaggerGenOptions.DocInclusionPredicate((version, desc) =>
                {
                    if (!desc.TryGetMethodInfo(out MethodInfo methodInfo))
                    {
                        return false;
                    }
                    var versions = methodInfo.DeclaringType.GetConstructors()
                        .SelectMany(constructorInfo => constructorInfo.DeclaringType.CustomAttributes
                            .Where(attributeData => attributeData.AttributeType == typeof(ApiVersionAttribute))
                            .SelectMany(attributeData => attributeData.ConstructorArguments
                                .Select(attributeTypedArgument => attributeTypedArgument.Value)));
    
                    return versions.Any(v => $"{v}" == version);
                });
    
                swaggerGenOptions.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"));
                
                ... some filter settings here 
            });
    

    In Startup#Configure

    var swaggerOptions = new SwaggerOptions();
    Configuration.GetSection("Swagger").Bind(swaggerOptions);
    app.UseSwagger(option => option.RouteTemplate = swaggerOptions.JsonRoute);
    
    app.UseSwaggerUI(option =>
    {
      foreach (var currentVersion in swaggerOptions.Versions)
      {
        option.SwaggerEndpoint(currentVersion.UiEndpoint, $"{swaggerOptions.Title} {currentVersion.Name}");
      }
    });
    

    appsettings.json

    {
      "Swagger": {
        "Title": "App title",
        "JsonRoute": "swagger/{documentName}/swagger.json",
        "Description": "Some text",
        "Versions": [
          {
            "Name": "2.0",
              "UiEndpoint": "/swagger/2.0/swagger.json"
          },
          {
            "Name": "1.0",
            "UiEndpoint": "/swagger/1.0/swagger.json"
          }
        ]
      }
    }
    

    This code is very similar to a related issue I'm working on here on SO.