简体   繁体   English

如何组合十字花式过滤器?

[英]How to combine Swashbuckle filters?

What I need is using some condition to hide or show some properties of a model in Model|Example Value of response in Swagger UI. 我需要使用某种条件在Swagger UI中的Model | Example响应中隐藏或显示模型的某些属性。

How could this be realized? 如何实现呢? My condition is based on attributes on api actions and on properties of a DTO. 我的条件基于api操作的属性和DTO的属性。 So, fe, if an action provides an attribute then we should only see the tagged properties in Swagger UI. 因此,例如,如果一个动作提供了一个属性,那么我们应该只在Swagger UI中看到标记的属性。

Solved. 解决了。 You only need to implement IOperationFilter and register it. 您只需要实现IOperationFilter并注册它。 This stuff allows you to show customized different examples for the same model. 这些东西使您可以显示同一模型的定制不同示例。


DTO DTO

public class MyDTO
{
    public int Id { get; set; }

    [ShortModelMember]
    public string Name { get; set; }
    ...
}   

Method in API controller API控制器中的方法

[HttpGet]
[ReturnShortModel]
public MyDTO GetSmthg()
{
    return MyDTO.GetExample();
}   

Swagger's custom operation filter Swagger的自定义操作过滤器

public class SwaggerExcludeFilter : IOperationFilter
{
    public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
    {
        if (!apiDescription.GetControllerAndActionAttributes<ReturnShortModelAttribute>().Any())
        {
            return;
        }

        var responseType = apiDescription.ResponseDescription.DeclaredType;
        var description = $"OK (uses a short model of {responseType})";
        var props = responseType
                    .GetProperties()
                    .Where(p => p.GetCustomAttributes(typeof(ShortModelMemberAttribute)).Any())
                    .ToDictionary(p => p.Name, p.PropertyType.Name);
        }

        operation.responses.Clear();
        operation.responses.Add("200", new Response
        {
            description = description,
            schema = new Schema
            {
                example = props,
            },
        });
    }
}   

And finally 最后

c.OperationFilter<SwaggerExcludeFilter>();   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM