Search code examples
c#asp.net-coreswaggerswagger-ui

Ignore Property From Swagger UI


I'm trying to ignore property on swagger UI. based on this article I have implemented a Filter and tried

[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
public class SwaggerExcludeAttribute : Attribute
{
}

public class SwaggerExcludeFilter : ISchemaFilter
{
    public void Apply(OpenApiSchema schema, SchemaFilterContext context)
    {
        if (schema?.Properties == null || context == null) return;
        var excludedProperties = context.Type.GetProperties()
            .Where(t => t.GetCustomAttribute(typeof(SwaggerExcludeAttribute), true) != null);
        foreach (var excludedProperty in excludedProperties)
        {
            if (schema.Properties.ContainsKey(excludedProperty.Name))
                schema.Properties.Remove(excludedProperty.Name);
        }
    }
}
  1. custom attribute seems not properly getting by reflection excludedProperties always empty.
  2. context.MemberInfo does read the property but cannot remove from schema.Properties because no properties there

my sample model is like

public class SequenceSetupListModel
{
    public int Id { get; set; }
    public int Sequence { get; set; }
    public string Role { get; set; }
    public string User { get; set; }
    [SwaggerExclude]
    public IList<Sequence> SequenceLists { get; set; }
}

What I'm missing here

Regards


Solution

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