首页 > 解决方案 > 如何组合 Swashbuckle 过滤器?

问题描述

我需要的是使用某些条件来隐藏或显示模型中模型的某些属性| Swagger UI 中响应的示例值

这怎么可能实现?我的条件基于 api 操作的属性和 DTO 的属性。所以,fe,如果一个动作提供了一个属性,那么我们应该只在 Swagger UI 中看到标记的属性。

标签: c#asp.net-web-apiswashbuckle

解决方案


解决了。您只需要实现IOperationFilter并注册它。这些东西允许您为同一模型显示定制的不同示例。


DTO

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

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

API 控制器中的方法

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

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

最后

c.OperationFilter<SwaggerExcludeFilter>();   

推荐阅读