ani*_*089 3 c# asp.net-web-api swagger swashbuckle asp.net-core-3.1
我们是从.NET 2.1的核心应用迁移到3.1,我们需要升级的过程中,从4.X招摇5.X为好。使用 swagger 4.x,我们能够删除某些用特定属性标记的属性,如下所示:
public class SwaggerIgnoreFilter : IDocumentFilter
{
public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
{
var allTypes = AppDomain.CurrentDomain.GetAssemblies().SelectMany(i => i.GetTypes()).ToList();
foreach (var definition in swaggerDoc?.Definitions)
{
var type = allTypes.FirstOrDefault(x => x.Name == definition.Key);
if (type != null)
{
var properties = type.GetProperties();
foreach (var prop in properties.ToList())
{
var ignoreAttribute = prop.GetCustomAttribute(typeof(SwaggerIgnoreAttribute), false);
if (ignoreAttribute != null)
{
definition.Value.Properties.Remove(prop.Name);
}
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
问题是,在 swagger 5.0 中,IDocumentFilter 发生了变化,我们用 OpenApiDocument 代替 SwaggerDocument,后者已经取消了Definitions属性,我们无法弄清楚如何从 swagger 页面隐藏某些属性。任何帮助/建议/链接都会很棒。谢谢。
现在你可以使用 swaggerDoc.Components.Schemas
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
{
var allTypes = AppDomain.CurrentDomain.GetAssemblies().SelectMany(i => i.GetTypes()).ToList();
foreach (var definition in swaggerDoc.Components.Schemas)
{
var type = allTypes.FirstOrDefault(x => x.Name == definition.Key);
if (type != null)
{
var properties = type.GetProperties();
foreach (var prop in properties.ToList())
{
var ignoreAttribute = prop.GetCustomAttribute(typeof(SwaggerIgnoreAttribute), false);
if (ignoreAttribute != null)
{
definition.Value.Properties.Remove(prop.Name);
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2198 次 |
| 最近记录: |