Swagger - hide api version parameters

Viewed 5850

Is it possible to hide the 'api-version' and 'x-api-version' parameters?

        services.AddApiVersioning(config =>
        {
            config.ReportApiVersions = true;
            config.DefaultApiVersion = new ApiVersion(1, 0);
            config.AssumeDefaultVersionWhenUnspecified = true;

            config.ApiVersionReader = ApiVersionReader.Combine(
             new QueryStringApiVersionReader(),
             new HeaderApiVersionReader()
             {
                 HeaderNames = { "x-api-version" }
             });
        });

        services.AddVersionedApiExplorer(
            options =>
            {
                // note: the specified format code will format the version as "'v'major[.minor][-status]"
                options.GroupNameFormat = "'v'VVV";

                options.DefaultApiVersionParameterDescription = "Do NOT modify api-version!";
            });

I already checked how-to-set-up-swashbuckle-vs-microsoft-aspnetcore-mvc-versioning which implements a 'RemoveVersionFromParameter' method, but in that case the Swagger page would loose the api version and always uses the default v1.0. As shown in the code snippet, I am using the QueryStringApiVersionReader and HeaderApiVersionReader, but I don't want to support the url api versioning.

Note: The API does have multiple swagger json pages for all versions (e.g. V1, V1.1, V2.0)

enter image description here

5 Answers

You can try an operation filter. This is similar to Helder's solution, but the implementation doesn't have to be at the document level, so it seems simpler:

public void Configure(SwaggerGenOptions options)
{
    // Filter out `api-version` parameters globally
    options.OperationFilter<ApiVersionFilter>();
}

internal class ApiVersionFilter : IOperationFilter
{
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        var parametersToRemove = operation.Parameters.Where(x => x.Name == "api-version").ToList();
        foreach (var parameter in parametersToRemove)
            operation.Parameters.Remove(parameter);
    }
}

You can add your own custom CSS and use it to hide those elements (and do any other customisation you want).

app.UseSwaggerUI(c =>
{
    ...
    c.InjectStylesheet("/swagger-ui/custom.css");
    ...
});

Edit - example:

Suppose you're trying to hide - in my example; you can easily adapt it to yours - the tenantId parameter in this "Remove Basket" operation:

enter image description here

This would do that:

div#operations-baskets-remove tr[data-param-name="tenantId"] {
    display: none;
}

Have you looked into IDocumentFilter with that you can remove stuff from the final swagger.json and that will remove it from the UI

Here is an example me removing some properties from the definitions:

    private class HideStuffDocumentFilter : IDocumentFilter
    {
        public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry s, IApiExplorer a)
        {
            foreach (var definition in swaggerDoc.definitions)
            {
                foreach (var prop in definition.Value.properties.ToList())
                {
                    if (prop.Value.maxLength == 9999)
                        definition.Value.properties.Remove(prop);
                }
            }
        }
    }

I have a few more samples here:
https://github.com/heldersepu/Swagger-Net-Test/blob/e701b1d20d0b42c1287c3da2641ca521a0a7b592/Swagger_Test/App_Start/SwaggerConfig.cs#L766

This can be done by setting ApiExplorerOption SubstituteApiVersionInUrl = true . In your case:

    services.AddVersionedApiExplorer(
        options =>
        {
            // note: the specified format code will format the version as "'v'major[.minor][-status]"
            options.GroupNameFormat = "'v'VVV";

            options.DefaultApiVersionParameterDescription = "Do NOT modify api-version!";
            options.SubstituteApiVersionInUrl = true;
        });

You can added startup.cs file.

services.AddApiVersioning(options =>
        {
            // reporting api versions will return the headers "api-supported-versions" and "api-deprecated-versions"
            options.ReportApiVersions = true;
        });


services.AddVersionedApiExplorer(options =>
        {
            // add the versioned api explorer, which also adds IApiVersionDescriptionProvider service
            // note: the specified format code will format the version as "'v'major[.minor][-status]"
            options.GroupNameFormat = "'v'VVV";

            // note: this option is only necessary when versioning by url segment. the SubstitutionFormat
            // can also be used to control the format of the API version in route templates
            options.SubstituteApiVersionInUrl = true;
        });

And then,you can added top on the controller. But I try to without this([ApiVersion("1.0")]),it could run.I had successfully hide version parametre.

[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/Check")]
[ApiController]
[Authorize]
public class CheckController : ControllerBase {}
Related