.Net Core 3.1 Remove Schema on Swagger UI

Viewed 12034

I have .Net 3.1 Web Api, I would like to remove this sections "Schemas" on Swagger UI.
How to do it? .net

4 Answers

No need for a schema filter. After busting on it for days I have found out:

All needs to be done is in

app.UseSwaggerUI(options =>
{
    options.DefaultModelsExpandDepth(-1);
});

Note: It is DefaultModels (plural) not DefaultModel (singular). Difference is DefaultModels is the default expansion depth for the model on the model-example section, whereas DefaultModels is the expansion depth for models.

On Adding Swagger UI just add the following line:

app.UseSwaggerUI(c => {
    c.DefaultModelsExpandDepth(-1);
});

After a lot of breaking my head, using the user's suggestion "CoffeeCodeConverterImpl" I made the class like this:

public class RemoveSchemasFilter : IDocumentFilter
{
    public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
    {
        
        IDictionary<string, OpenApiSchema> _remove = swaggerDoc.Components.Schemas;
        foreach (KeyValuePair<string, OpenApiSchema> _item in _remove)
        {
            swaggerDoc.Components.Schemas.Remove(_item.Key);
        }
    }
}

Implementation:

 c.DocumentFilter<RemoveSchemasFilter>();

Add a custom IDocumentFilter implementation to your swagger configuration:

services.AddSwaggerGen(options => options.DocumentFilter<RemoveSchemasFilter>());

In the Apply method of RemoveSchemasFilter you should then be able to identify the elements of the OpenApiDocument you want to remove and do so accordingly.

Related