How to configure Swashbuckle to ignore property on model

后端 未结 15 1770
旧巷少年郎
旧巷少年郎 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:57

    The code below is very much based on @Richard's answer, but I am including it as a new answer because it has three completely new, useful features which I have added:

    • Runs on .NET Core on the latest version of Swashbuckle (v5)
    • Allows the SwaggerIgnore attribute to be applied to fields not just to properties
    • Handles the fact that property and field names may have been overridden using the JsonProperty attribute
    • EDIT: Now correctly handles camelCasing of originally TitleCased fields or properties (prompted by @mattruma's answer)

    So the revised code is:

    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
    public class SwaggerIgnoreAttribute : Attribute
    {
    }
    
    internal static class StringExtensions
    {
        internal static string ToCamelCase(this string value)
        {
            if (string.IsNullOrEmpty(value)) return value;
            return char.ToLowerInvariant(value[0]) + value.Substring(1);
        }
    }
    
    public class SwaggerIgnoreFilter : ISchemaFilter
    {
        public void Apply(OpenApiSchema schema, SchemaFilterContext schemaFilterContext)
        {
            if (schema.Properties.Count == 0)
                return;
    
            const BindingFlags bindingFlags = BindingFlags.Public |
                                              BindingFlags.NonPublic |
                                              BindingFlags.Instance;
            var memberList = schemaFilterContext.SystemType
                                .GetFields(bindingFlags).Cast()
                                .Concat(schemaFilterContext.SystemType
                                .GetProperties(bindingFlags));
    
            var excludedList = memberList.Where(m =>
                                                m.GetCustomAttribute()
                                                != null)
                                         .Select(m =>
                                             (m.GetCustomAttribute()
                                              ?.PropertyName
                                              ?? m.Name.ToCamelCase()));
    
            foreach (var excludedName in excludedList)
            {
                if (schema.Properties.ContainsKey(excludedName))
                    schema.Properties.Remove(excludedName);
            }
        }
    }
    

    and in Startup.cs:

    services.AddSwaggerGen(c =>
    {
        ...
        c.SchemaFilter();
        ...
    });
    

提交回复
热议问题