如何配置 Swashbuckle 以从文档中省略模板/实体/架构

How to configure Swashbuckle to omit Template / Entity / Schema from the documentation

我正在尝试为 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);
    }
}

引用:

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

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

app.UseSwaggerUI(c =>
{
    ...
    c.DefaultModelsExpandDepth(-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);
        }
    }
}