Leverage MultipleApiVersions in Swagger with attribute versioning

8.5k views Asked by At

Is it possible to leverage MultipleApiVersions in Swagger UI / Swashbuckle when using attribute routing?

Specifically, I implemented versioning by:

using System.Web.Http;

namespace RESTServices.Controllers.v1
{
    [Route("api/v1/Test")]
    public class TestV1Controller : ApiController
    { ... }

Version 2 would be in a v2 namespace. In a controller named TestV2Controller. The route would have v2 in it.

Is it possible to pass a lambda in that will allow this? I found a sample lambda online which compiled, but then Swagger stopped working completely. Couldn't hit breakpoints or see Swagger in the browser.

2

There are 2 answers

3
Hoppe On BEST ANSWER
.EnableSwagger(c => c.MultipleApiVersions(
        (apiDesc, version) =>
        {
            var path = apiDesc.RelativePath.Split('/');
            var pathVersion = path[1];

            return CultureInfo.InvariantCulture.CompareInfo.IndexOf(pathVersion, version, CompareOptions.IgnoreCase) >= 0;
        },
        vc =>
        {
            vc.Version("v2", "Swashbuckle Dummy API V2"); //add this line when v2 is released

            // ReSharper disable once ConvertToLambdaExpression
            vc.Version("v1", "Swashbuckle Dummy API V1");
        }
        ))
2
Rohit Vipin Mathews On

Swagger supports multiple versions. Configure the URL such that Swagger can specify the version correctly.

httpConfiguration
.EnableSwagger(c =>
    {
        c.MultipleApiVersions(
            (apiDesc, targetApiVersion) => ResolveVersionSupportByRouteConstraint(apiDesc, targetApiVersion),
            (vc) =>
            {
                vc.Version("v2", "Swashbuckle Dummy API V2");
                vc.Version("v1", "Swashbuckle Dummy API V1");
            });
    });
.EnableSwaggerUi(c =>
    {
        c.EnableDiscoveryUrlSelector();
    });


    private static bool ResolveVersionSupportByRouteConstraint(ApiDescription apiDesc, string targetApiVersion)
    {
        return apiDesc.ActionDescriptor.ControllerDescriptor.ControllerType.FullName.Contains($"{targetApiVersion}.");
    }

References: