如何配置Swashbuckle以忽略模型上的属性 [英] How to configure Swashbuckle to ignore property on model

查看:211
本文介绍了如何配置Swashbuckle以忽略模型上的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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以忽略模型上的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆