.net Swagger -隐藏api版本参数

pw9qyyiw  于 2022-11-26  发布在  .NET
关注(0)|答案(6)|浏览(225)

是否可以隐藏“api-version”和“x-api-version”参数?

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!";
            });

我已经检查了how-to-set-up-swashbuckle-vs-microsoft-aspnetcore-mvc-versioning,它实现了一个'RemoveVersionFromParameter'方法,但在这种情况下,Swagger页面将失去API版本,并始终使用默认的v1.0。如代码片段所示,我正在使用QueryStringApiVersionReader和HeaderApiVersionReader,但我不想支持url API版本控制。
注:API的所有版本(例如V1、V1.1、V2.0)都有多个swagger json页面

yqyhoc1h

yqyhoc1h1#

你可以尝试一个操作过滤器。这类似于Helder的解决方案,但是实现不必在文档级别,所以看起来更简单:

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);
    }
}
n1bvdmb6

n1bvdmb62#

你有没有研究过IDocumentFilter,你可以从最终的swagger.json中删除一些东西,这样就可以从UI中删除它
下面是从定义中删除一些属性的示例:

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);
                }
            }
        }
    }

我这里还有一些样品:
https://github.com/heldersepu/Swagger-Net-Test/blob/e701b1d20d0b42c1287c3da2641ca521a0a7b592/Swagger_Test/App_Start/SwaggerConfig.cs#L766

bxpogfeg

bxpogfeg3#

您可以添加自己的自定义CSS,并使用它来隐藏这些元素(并进行任何其他您想要的自定义)。

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

编辑-示例:

假设你试图隐藏--在我的例子中;您可以轻松地将其调整为适合您的-“Remove Basket”操作中的tenantId参数:

这将实现以下目的:

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

hiz5n14c4#

这可以通过设置ApiExplorerOptionSubstituteApiVersionInUrl = true来完成。在您的情况下:

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;
        });
y1aodyip

y1aodyip5#

这对我很管用。

public class SwaggerOperationFilter : IOperationFilter
{
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        if (operation?.Parameters == null
            || !operation.Parameters.Any())
        {
            return;
        }

        var parametersWithPropertiesToIgnore = context.ApiDescription
            .ActionDescriptor.Parameters.Where(p =>
                p.ParameterType.GetProperties()
                    .Any(t => t.GetCustomAttribute<IgnoreDataMemberAttribute>() != null));

        foreach (var parameter in parametersWithPropertiesToIgnore)
        {
            var ignoreDataMemberProperties = parameter.ParameterType.GetProperties()
                .Where(t => t.GetCustomAttribute<IgnoreDataMemberAttribute>() != null)
                .Select(p => p.Name);

            operation.Parameters = operation.Parameters.Where(p => !ignoreDataMemberProperties.Contains(p.Name))
                .ToList();
        }
    }
}

启动时

services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo { Title = "Api", Version = "v1" });
            c.SchemaFilter<SwaggerSchemaFilter>();
            c.OperationFilter<SwaggerOperationFilter>();

            var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
            var filePath = Path.Combine(System.AppContext.BaseDirectory, xmlFile);
            c.IncludeXmlComments(filePath);
        });

只需在属性中添加数据注解[IgnoreDataMember]即可将其隐藏。

public class ExampleRequest
{

    [IgnoreDataMember]
    public string? HiddenProp { get; set; }

    public string OtherProp { get; set; }
}

我已经基于this article创建了这个解决方案。

drnojrws

drnojrws6#

您可以添加startup.cs文件。

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;
        });

然后,你可以在控制器上添加顶部。但我试图没有这个([ApiVersion(“1.0”)]),它可以运行。我已经成功地隐藏版本参数。

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

相关问题