问题描述
我正在使用Swashbuckle为一个webapi2项目生成swagger文档\ UI.我们的模型与一些旧版接口共享,因此我想在模型上忽略几个属性.我不能使用JsonIgnore属性,因为旧版接口还需要序列化为JSON,所以我不想只在Swashbuckle配置中全局忽略属性.
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 want to ignore on the models. I can't use JsonIgnore attribute because the legacy interfaces also need to serialize to JSON so I don't want to ignore the properties globally, just in the Swashbuckle configuration.
我找到了一种记录在这里的方法:
I found a method of doing this documented here:
https://github.com/domaindrivendev/Swashbuckle/issues/73
但是,这似乎与当前的Swashbuckle版本已过时.
But this appears to be out of date with the current Swashbuckle release.
为旧版本的Swashbuckle推荐的方法是使用IModelFilter实现,如下所示:
The method recommended for the old version of Swashbuckle is using an IModelFilter implementation as follows:
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.
But I'm unsure how to configure Swashbuckle to use the IModelFilter in the current version? I'm using Swashbuckle 5.5.3.
推荐答案
如果您需要执行此操作但不使用JsonIgnore(也许您仍需要序列化/反序列化该属性),则只需创建一个自定义属性即可.
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
{
}
然后使用类似于约翰的
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>();
这篇关于如何配置Swashbuckle以忽略模型上的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!