问题描述
我正在使用 Swashbuckle 为 webapi2 项目生成 swagger 文档UI.我们的模型与一些遗留接口共享,因此我想忽略模型上的几个属性.我不能使用 JsonIgnore 属性,因为遗留接口也需要序列化为 JSON,所以我不想全局忽略这些属性,只是在 Swashbuckle 配置中.
I'm using Swashbuckle to generate swagger documentationUI 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
{
}
然后是类似于 John'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
}
别忘了注册过滤器
c.SchemaFilter<SwaggerExcludeFilter>();
这篇关于如何配置 Swashbuckle 以忽略模型上的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!