我正在使用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。
如果您需要执行此操作但不使用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>();
看来这仅适用于输出模型?当我将此代码应用于输入模型(由GET使用)时,找不到该模型吗?
Swashbuckle.AspNetCore.SwaggerGen.ISchemaFilter没有类型参数。如何在那里解决?
我发布了一项修改,使其可以在最新的dotnetcore上运行。
使用这种区分大小写的解决方案时,我遇到了一个问题。我的POCO中的属性名称位于PascalCase中,而序列化对象的名称位于camelCase中,因此,代替ContainsKey,检查var foundKey = schema.properties.Keys.FirstOrDefault(x => string.Equals(x ,excludeProperty.Name,StringComparison.CurrentCultureIgnoreCase));
@Richard这是一个非常有用的答案。我已经发布了它的一个更新的版本如下,其中:工程对Swashbuckle的最新(V5)版本; 可以应用于字段以及属性;尊重
JsonProperty
属性可能对数据成员进行的重命名。谢谢!