简体   繁体   中英

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.

How could this be realized? My condition is based on attributes on api actions and on properties of a DTO. So, fe, if an action provides an attribute then we should only see the tagged properties in Swagger UI.

Solved. You only need to implement IOperationFilter and register it. This stuff allows you to show customized different examples for the same model.


DTO

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

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

Method in API controller

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

Swagger's custom operation filter

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>();   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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