0

I have a ASP.Net Core Web API with Swagger configured that shows the API End Points.Also API Versioning is enabled. However, the swagger UI is not populating the mandatory field Version when checking the End Point.See image below:

Is it possible to populate this field automatically by code given that the API Action already configures this value i.e. the MaptoApiVersion. In theory this field should be populated automatically??

    [MapToApiVersion("2")]
    [HttpGet("GetV2")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status500InternalServerError)]
    public async Task<IEnumerable<TodoDto>> GetV2()
    {
        var query = new AllTodosQuery(_context);
        var todos = await query.ExecuteAsync();
        return todos;
    }

enter image description here

user1829319
  • 691
  • 1
  • 8
  • 22

1 Answers1

1

The issue is at least two-fold. First, the extensions to the API Explorer from API Versioning do provide the version parameter with a default value, but many Swagger/OpenAPI generators (such as Swashbuckle) still do not yet honor it. If you want to enable this behavior, you need a custom IOperationFilter which does something to the effect of:

var parameter = operation.Parameters.First(p => p.Name == "version");
var description = context.ApiDescription.ParameterDescriptions.First(p => p.Name == "version");

if (parameter.Schema.Default == null && description.DefaultValue != null)
{
    parameter.Schema.Default = new OpenApiString(description.DefaultValue.ToString());
}

You can find a complete end-to-end example in the API Versioning repo in: SwaggerDefaultValues.cs

Since you're versioning by URL segment, if you want that inlined into the route template without a corresponding parameter, you need only configure the API Explorer extensions to do so like this:

services.AddVersionedApiExplorer(options => options.SubstituteApiVersionInUrl = true);

This option only applies to the URL segment versioning method.

A complete end-to-end Swashbuckle example with API Versioning can be found inside Startup.cs inside the repo.

Chris Martinez
  • 3,185
  • 12
  • 28