Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swagger 5.0 - IDocumentFilter (SwaggerDocument to OpenApiDocument) custom "Definitions"

We are in process of migrating the application from .NET Core 2.1 to 3.1 for which we need to upgrade swagger from 4.X to 5.X as well. With swagger 4.x we were able to remove certain properties that were marked with a specific attribute with something like the following:

public class SwaggerIgnoreFilter : IDocumentFilter
{
    public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
    {
        var allTypes = AppDomain.CurrentDomain.GetAssemblies().SelectMany(i => i.GetTypes()).ToList();

        foreach (var definition in swaggerDoc?.Definitions)
        {
            var type = allTypes.FirstOrDefault(x => x.Name == definition.Key);
            if (type != null)
            {
                var properties = type.GetProperties();
                foreach (var prop in properties.ToList())
                {
                    var ignoreAttribute = prop.GetCustomAttribute(typeof(SwaggerIgnoreAttribute), false);

                    if (ignoreAttribute != null)
                    {
                        definition.Value.Properties.Remove(prop.Name);
                    }
                }
            }
        }
    }
}

The problem is that with swagger 5.0, the IDocumentFilter has changed and we have OpenApiDocument in place of SwaggerDocument which has taken away Definitions property and we are unable to figure out how to hide certain properties from the swagger pages. Any help/suggestion/link would be great. Thanks.

like image 668
animat089 Avatar asked Aug 01 '26 07:08

animat089


1 Answers

Now you can use swaggerDoc.Components.Schemas

public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
{
    var allTypes = AppDomain.CurrentDomain.GetAssemblies().SelectMany(i => i.GetTypes()).ToList();

    foreach (var definition in swaggerDoc.Components.Schemas)
    {
        var type = allTypes.FirstOrDefault(x => x.Name == definition.Key);
        if (type != null)
        {
            var properties = type.GetProperties();
            foreach (var prop in properties.ToList())
            {
                var ignoreAttribute = prop.GetCustomAttribute(typeof(SwaggerIgnoreAttribute), false);

                if (ignoreAttribute != null)
                {
                    definition.Value.Properties.Remove(prop.Name);
                }
            }
        }
    }
}
like image 179
Roman Marusyk Avatar answered Aug 02 '26 21:08

Roman Marusyk