【问题标题】:How to exclude certain model from Swagger UI如何从 Swagger UI 中排除某些模型
【发布时间】:2022-01-27 21:06:47
【问题描述】:

我有一个模型正在被其他模型之一使用,它被接受为我的一个控制器的参数。因此,该模型正在 Swagger UI 中显示。这个模型是一个可以为空的类型并且是可选的,我想在我的文档中隐藏它。

public class A 
{
    public string SomeProperty { get; set; }
    public B? ClassB {get; set; }
}

public class B 
{
    public int SomeIntProperty { get; set; }
    public bool SomeBooleanProperty { get; set; }
}

在控制器方法中:

    public async Task<ActionResult<SomeType>> GetSomeType(A modelA, CancellationToken token)

按原样,此端点将接受如下 JSON 文档:

{
     "SomeProperty": "SomeValue"
}

并且不需要 B 在场。因此,我想从我的 Swagger 模式中隐藏 B。我怎样才能做到这一点?我找到了一些相关的问题/答案,但都是关于隐藏属性的,https://stackoverflow.com/a/48454933/16749442

隐藏模型的所有属性会导致模型为空:

【问题讨论】:

  • 使用视图模型
  • 最好的答案是不要对两种不同的事物使用相同的模型。只需创建一个没有您要排除的属性的新模型。

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


【解决方案1】:

不幸的是,我发现的唯一有效且干净的解决方案是再次使用反射。

SwaggerExcludeAttribute.cs

[AttributeUsage(AttributeTargets.Class)]
public class SwaggerExcludeAttribute : Attribute
{
}

SwaggerIgnoreModelFilter.cs

public class SwaggerIgnoreModelFilter : IDocumentFilter
{
    public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
    {
        // Get all models that are decorated with SwaggerExcludeAttribute
        // This will only work for models that are under current Assembly
        var excludedTypes = GetTypesWithHelpAttribute(Assembly.GetExecutingAssembly());
        // Loop through them
        foreach (var _type in excludedTypes)
        {
            // Check if that type exists in SchemaRepository
            if (context.SchemaRepository.TryLookupByType(_type, out _))
            {
                // If the type exists in SchemaRepository, check if name exists in the dictionary
                if (swaggerDoc.Components.Schemas.ContainsKey(_type.Name))
                {
                    // Remove the schema
                    swaggerDoc.Components.Schemas.Remove(_type.Name);
                }
            }
        }
    }

    // Get all types in assembly that contains SwaggerExcludeAttribute
    public static IEnumerable<Type> GetTypesWithHelpAttribute(Assembly assembly)
    {
        return assembly.GetTypes().Where(type => type.GetCustomAttributes(typeof(SwaggerExcludeAttribute), true).Length > 0);
    }
}

Startup.cs

services.AddSwaggerGen(c =>
{
    .....
    c.DocumentFilter<SwaggerIgnoreModelFilter>();
    ......
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-08
    • 2021-03-30
    • 2018-11-28
    • 2022-10-19
    • 2021-07-02
    • 2011-06-05
    相关资源
    最近更新 更多