I use ASP.Net Core WebApi, Swashbuckle and Microsoft.AspNetCore.Mvc.Versioning to document and versioning my API.
The versioning also works so far.
My Problem:
The generated Swagger UI Document does not include parameters (Request-Header or Query Parameter) to determine the version of the Endpoint. So when i press "Execute" in the Swagger-Document the wrong version (default version) is picked for the endpoint.
To be precise:
Swagger executes this request: https://localhost:5001/values
But, it should execute this requerst: https://localhost:5001/values?api-version=2.0
Code:
Controller:
[ApiController]
[Route("[controller]")]
[SwaggerTag("Gets some values. Have fun with it")]
[ApiVersion("1.0")]
[ApiVersion("2.0")]
public class ValuesController : ControllerBase
{
public ValuesController()
{
}
/// <summary>
/// Gets all values
/// </summary>
/// <remarks>There are values from 1 to 10</remarks>
/// <returns></returns>
[HttpGet]
[SwaggerResponse(200, "Request was successful a list of values was returned", typeof(int[]))]
[MapToApiVersion("1.0")]
public async Task<IActionResult> Get()
{
return Ok(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });
}
/// <summary>
/// Gets all values
/// </summary>
/// <remarks>There are values from 1 to 20</remarks>
/// <returns></returns>
[HttpGet]
[SwaggerOperation(Tags = new[] { "Values", "Changed Endpoints" })]
[SwaggerResponse(200, "Request was successful a list of values was returned", typeof(int[]))]
[MapToApiVersion("2.0")]
public async Task<IActionResult> Getv2()
{
return Ok(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 });
}
Enable versioning:
services.AddApiVersioning(config =>
{
config.DefaultApiVersion = new ApiVersion(1, 0);
config.AssumeDefaultVersionWhenUnspecified = true;
config.ReportApiVersions = true;
config.ApiVersionReader = ApiVersionReader.Combine(new QueryStringApiVersionReader(),
new HeaderApiVersionReader()
{
HeaderNames = { "x-api-version" }
});
});
Enable SwaggerGen:
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("1.0", new OpenApiInfo
{
Title = "API v1.0",
Version = "1.0",
});
c.SwaggerDoc("2.0", new OpenApiInfo
{
Title = "API v1.0",
Version = "1.0",
});
c.EnableAnnotations();
c.IncludeXmlComments(System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "wwwroot", "OpenApi.xml"));
c.DocInclusionPredicate((docName, apiDesc) =>
{
if (!apiDesc.TryGetMethodInfo(out MethodInfo methodInfo)) return false;
var versions = methodInfo.GetCustomAttributes(true)
.OfType<Microsoft.AspNetCore.Mvc.MapToApiVersionAttribute>()
.SelectMany(attr => attr.Versions).ToList();
return versions.Any(v => v.ToString() == docName);
});
});
Can someone help me?

