【问题标题】:How to configure Swashbuckle to omit Template / Entity / Schema from the documentation如何配置 Swashbuckle 以从文档中省略模板/实体/架构
【发布时间】:2020-05-26 08:06:38
【问题描述】:

我正在尝试为 Swashbuckle 构建一个过滤器,以在 API 文档中省略项目的模型/实体/架构,保留控制器。采用的技术是 Swashbuckle.AspNetCore v3.0.0 / Swagger UI v3.17.1。我已经找到了在控制器中省略某个方法的方法,但我想省略文档中的模型。我发现了一个和我类似的问题,包括只隐藏属性。

跟随过滤器代码

public void Apply(OpenApiSchema schema, SchemaFilterContext context)
{
    if (!(context.ApiModel is ApiObject))
    {
        return;
    }

    var model = context as ApiObject;

    if (schema?.Properties == null || model?.ApiProperties == null)
    {
        return;
    }

    var excludedProperties = model.Type
        .GetProperties()
        .Where(
            t => t.GetCustomAttribute<SwaggerExcludeAttribute>() != null
        );

    var excludedSchemaProperties = model.ApiProperties
        .Where(
            ap => excludedProperties.Any(
                pi => pi.Name == ap.MemberInfo.Name
            )
        );

    foreach (var propertyToExclude in excludedSchemaProperties)
    {
         schema.Properties.Remove(propertyToExclude.ApiName);
    }
}

引用:How to configure Swashbuckle to ignore property on model

有人有什么建议可以只隐藏文档中的模型/实体/模式,而不仅仅是它们的属性吗?如下图。

【问题讨论】:

标签: .net-core swagger swagger-ui swashbuckle


【解决方案1】:

至少对我来说,我必须这样做:

internal class SwaggerSchemaFilter : ISchemaFilter
{
    public void Apply(OpenApiSchema schema, SchemaFilterContext context)
    {
        var keys = new System.Collections.Generic.List<string>();
        var prefix = "My.Prefix";
        foreach(var key in context.SchemaRepository.Schemas.Keys)
        {
            if (key.StartsWith(prefix))
            {
                keys.Add(key);
            }
        }

        foreach(var key in keys)
        {
            context.SchemaRepository.Schemas.Remove(key);
        }
    }
}

【讨论】:

    【解决方案2】:

    在 Swashbuckle / Swagger UI 配置中将 DefaultModelsExpandDepth 设置为 -1:

    app.UseSwaggerUI(c =>
    {
        ...
        c.DefaultModelsExpandDepth(-1);
    }
    

    【讨论】:

    • 感谢您的建议!但是在使用这行代码时,并没有达到预期的目标,即从文档中省略架构/实体/模型。
    • 请确保您使用的是DefaultModel*s*...(带有“s”)而不是DefaultModel...
    • DefaultModelExpandDepthDefaultModelRenderingDefaultModelsExpandDepth有什么区别?它们的名字看起来很相似,它们有相似的功能吗?
    • @liang 请参阅 Swagger UI 文档了解每个配置选项的描述github.com/swagger-api/swagger-ui/blob/master/docs/usage/…
    猜你喜欢
    • 2015-06-24
    • 2017-04-21
    • 2020-05-04
    • 2014-07-17
    • 1970-01-01
    • 2011-02-24
    • 2012-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多