How to Configure Swashbuckle to Ignore Property on Model

How to configure Swashbuckle to ignore property on model

If you need to do this but without using JsonIgnore (maybe you still need to serialize/deserialize the property) then just create a custom attribute.

[AttributeUsage(AttributeTargets.Property)]
public class SwaggerExcludeAttribute : Attribute
{
}

Then a schema filter similar to Johng's

public class SwaggerExcludeFilter : ISchemaFilter
{
#region ISchemaFilter Members

public void Apply(Schema schema, SchemaRegistry schemaRegistry, Type type)
{
if (schema?.properties == null || type == null)
return;

var excludedProperties = type.GetProperties()
.Where(t =>
t.GetCustomAttribute<SwaggerExcludeAttribute>()
!= null);

foreach (var excludedProperty in excludedProperties)
{
if (schema.properties.ContainsKey(excludedProperty.Name))
schema.properties.Remove(excludedProperty.Name);
}
}

#endregion
}

Don't forget to register the filter

c.SchemaFilter<SwaggerExcludeFilter>();

Ignore Property From Swagger UI

You don't actually need to define own attribute for request models. If you are using Json.NET then use [JsonIgnore]

Can I ignore a property in an ASP.Net Core API model?

If you're using Swashbuckle, you could install the Swashbuckle.AspNetCore.Annotations NuGet package, then use the SwaggerSchema attribute as follows:

namespace Models
{
public class Car
{
[SwaggerSchema(ReadOnly = true)]
public guid Id { get; set; }

public string Name { get; set; }
}
}

This will mark the property with the ReadOnly attribute in the generated OpenAPI document.

How to configure Swashbuckle to omit Template / Entity / Schema from the documentation

Set DefaultModelsExpandDepth to -1 in your Swashbuckle / Swagger UI configuration:

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


Related Topics



Leave a reply



Submit