I'm trying to build a filter for Swashbuckle to omit in the API documentation the models / Entities / Schema of the project, keeping the controllers. The technology employed is Swashbuckle.AspNetCore v3.0.0 / Swagger UI v3.17.1. I already found ways to omit a certain method in the controller, but I wanted to omit the models in the documentation. I found a problem similar to mine, including hiding only the properties.
Follow filter code
public void Apply(OpenApiSchema schema, SchemaFilterContext context)
{
if (!(context.ApiModel is ApiObject))
{
return;
}
var model = context as ApiObject;
if (schema?.Properties == null || model?.ApiProperties == null)
{
return;
}
var excludedProperties = model.Type
.GetProperties()
.Where(
t => t.GetCustomAttribute<SwaggerExcludeAttribute>() != null
);
var excludedSchemaProperties = model.ApiProperties
.Where(
ap => excludedProperties.Any(
pi => pi.Name == ap.MemberInfo.Name
)
);
foreach (var propertyToExclude in excludedSchemaProperties)
{
schema.Properties.Remove(propertyToExclude.ApiName);
}
}
quote: How to configure Swashbuckle to ignore property on model
Would anyone have any suggestions to hide only the models / Entities / Schemas from the documentation and not just their attributes? As the image below.
Set DefaultModelsExpandDepth
to -1 in your Swashbuckle / Swagger UI configuration:
app.UseSwaggerUI(c =>
{
...
c.DefaultModelsExpandDepth(-1);
}
At least for me I had to do something like:
internal class SwaggerSchemaFilter : ISchemaFilter
{
public void Apply(OpenApiSchema schema, SchemaFilterContext context)
{
var keys = new System.Collections.Generic.List<string>();
var prefix = "My.Prefix";
foreach(var key in context.SchemaRepository.Schemas.Keys)
{
if (key.StartsWith(prefix))
{
keys.Add(key);
}
}
foreach(var key in keys)
{
context.SchemaRepository.Schemas.Remove(key);
}
}
}
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.