温馨提示:本文翻译自stackoverflow.com,查看原文请点击:c# - How to configure Swashbuckle to ignore property on model
asp.net-web-api c# swagger swashbuckle

c# - 如何配置Swashbuckle以忽略模型上的属性

发布于 2020-03-27 10:58:41

我正在使用Swashbuckle为webapi2项目生成swagger文档\ UI。我们的模型与某些旧版接口共享,因此我想在模型上忽略几个属性。我不能使用JsonIgnore属性,因为旧式接口还需要序列化为JSON,所以我不想只在Swashbuckle配置中忽略全局属性。

我发现在此处记录了执行此操作的方法:

https://github.com/domaindrivendev/Swashbuckle/issues/73

但这似乎与当前的Swashbuckle版本已过时。

对于旧版本的Swashbuckle推荐的方法是使用IModelFilter实现,如下所示:

public class OmitIgnoredProperties : IModelFilter
{
    public void Apply(DataType model, DataTypeRegistry dataTypeRegistry, Type type)
    {
        var ignoredProperties = … // use reflection to find any properties on 
                                  // type decorated with the ignore attributes

        foreach (var prop in ignoredProperties) 
            model.Properties.Remove(prop.Name);

    }
}

SwaggerSpecConfig.Customize(c => c.ModelFilter<OmitIgnoredProperties>());

但是我不确定如何配置Swashbuckle在当前版本中使用IModelFilter?我正在使用Swashbuckle 5.5.3。

查看更多

查看更多

提问者
mutex
被浏览
204
19.3k 2018-04-30 00:50

如果您需要执行此操作但不使用JsonIgnore(也许仍然需要序列化/反序列化该属性),则只需创建一个自定义属性即可。

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

然后是类似于Johng的模式过滤器

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
}

不要忘记注册过滤器

c.SchemaFilter<SwaggerExcludeFilter>();