How to configure Swashbuckle to ignore property on model

后端 未结 15 1771
旧巷少年郎
旧巷少年郎 2020-12-02 15:10

I\'m using Swashbuckle to generate swagger documentation\\UI for a webapi2 project. Our models are shared with some legacy interfaces so there are a couple of properties I

15条回答
  •  时光说笑
    2020-12-02 15:55

    Based on Stef Heyenrath's answer.

    Attribute to mark properties to exclude from the Swagger documentation.

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

    The filter to exclude the properties from the Swagger documentation.

    public class SwaggerExcludeSchemaFilter : ISchemaFilter
    {
        public void Apply(Schema schema, SchemaFilterContext context)
        {
            if (schema?.Properties == null)
            {
                return;
            }
    
            var excludedProperties = 
                context.SystemType.GetProperties().Where(
                    t => t.GetCustomAttribute() != null);
    
            foreach (var excludedProperty in excludedProperties)
            {
                var propertyToRemove =
                    schema.Properties.Keys.SingleOrDefault(
                        x => x.ToLower() == excludedProperty.Name.ToLower());
    
                if (propertyToRemove != null)
                {
                    schema.Properties.Remove(propertyToRemove);
                }
            }
        }
    }
    

    The schema.Properties.Keys are camelCase, while the properties themselves are PascalCase. Tweaked the method to convert both to lower case and compare to see what should be excluded.

提交回复
热议问题