How to configure Swashbuckle to ignore property on model

后端 未结 15 1711
旧巷少年郎
旧巷少年郎 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 16:13

    Solution for .NET Core 3.1 and .NET Standard 2.1:

    Use JsonIgnore from System.Text.Json.Serialization namespace.

    ( JsonIgnore from Newtonsoft.Json will NOT work )

    public class Test
    {
        [System.Text.Json.Serialization.JsonIgnore]
        public int HiddenProperty { get; set; }
        public int VisibleProperty { get; set; }
    }
    
    0 讨论(0)
  • 2020-12-02 16:14

    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>();
    
    0 讨论(0)
  • 2020-12-02 16:14

    (Based on mutex's answer.)

    I added another line to not have problems with NullReferenceException.

    public void Apply(Schema schema, SchemaRegistry schemaRegistry, Type type)
    {
      var excludeProperties = new[] { "myProp1", "myProp2, myProp3"};
    
       foreach (var prop in excludeProperties)
         if(schema.properties != null) // This line
           if (schema.properties.ContainsKey(prop))
            schema.properties.Remove(prop);        
    }

    If you want to delete all schemas

    public void Apply(Schema schema, SchemaRegistry schemaRegistry, Type type)
    {
      schema.properties = null;       
    } 
    
    0 讨论(0)
提交回复
热议问题