Search code examples
c#asp.net-web-apiswaggerswashbuckleapi-versioning

How can I supply a path parameter to the displayed path in SwaggerUi?


I have setup Swagger/Swashbuckle on my WebAPI project. I have followed the guide from Microsoft which covers how to setup Aspnet.WebApi.Versioning with Swagger. My API has multiple versions, so there is a {version} parameter set in the route attributes, like this:

[ApiVersion("2")]
[RoutePrefix("api/{version:apiVersion}/values")]
public class AccountController : ApiController
{
    [Route("UserInfo")]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }
}

My issue is that this shows a {version} attribute in the path shown in the docs, like this:

enter image description here

Instead I want this path attribute to actually have the value in the ApiVersion attribute, so that there can be no confusion for the clients who read the documentation. Ideally, given that the UrlDiscoverySelector is set to v2 the paths above should be:

/api/2/account/userinfo
/api/2/account/externallogin
/api/2/account/manageinfo

My attempts to simply replace the {version} in the RelativePath of the ApiExplorer worked in the UI, but broke the test functionality as {version} was changed to a query parameter instead of a path, which is not how my API is configured.

Is it possible I can amend the values in the ApiExplorer before swagger builds the documentation while still retaining test functionality?


Solution

  • The API Explorer for API versioning now supports the behavior out-of-the-box using:

    options.SubstituteApiVersionInUrl = true
    

    This will do the substitution work for you and removes the API version parameter from the action descriptor. You generally don't need to change the default format applied to the substituted value, but you can change it using:

    options.SubstitutionFormat = "VVV"; // this is the default