如何将Swashbuckle配置为仅针对特定api版本忽略模型上的属性



我需要向模型添加一个属性,我已经实现了这里所选答案中的建议,它的工作原理是删除了我用模型的SwaggerIgnorePropertyAttribute属性标记的属性。我的问题是,如果我有几个API版本的应用程序,如何将其从特定版本的swaggerdoc/schema中删除?我只是不想大摇大摆地看到增加的财产。尽管我有几个版本的应用程序,但我在整个应用程序中实际上只有一个版本的模型。

我添加了这样的版本:

services.AddSwaggerGen(
swaggerOptions =>
{
swaggerOptions.SwaggerDoc(
"v1",
new Info
{
Title = "Titlebla1",
Description = "bla1",
Version = "v1"
});
swaggerOptions.SwaggerDoc(
"v2",
new Info
{
Title = "Titlebla2",
Description = "bla2",
Version = "v2"
});
etc

我知道我可以通过使用SwaggerDocument并执行以下操作来找到版本:swaggerDoc.Info.Version,但我如何从下面SwaggerExcludePropertySchemaFilter类中的Apply访问SwaggerDocument?

private class SwaggerExcludePropertySchemaFilter : ISchemaFilter
{
public void Apply(Schema schema, SchemaFilterContext context)
{
if (schema?.Properties == null)
{
return;
}
var excludedProperties = context.SystemType.GetProperties().Where(t => t.GetCustomAttribute<SwaggerIgnorePropertyAttribute>() != null);
foreach (var excludedProperty in excludedProperties)
{
var propertyToRemove = schema.Properties.Keys.SingleOrDefault(x => string.Equals(x, excludedProperty.Name, StringComparison.OrdinalIgnoreCase));
if (propertyToRemove != null)
{
schema.Properties.Remove(propertyToRemove);
}
}
}
}

尝试使用IDocumentFilter,请参阅示例:

public class CustomSwaggerFilter : IDocumentFilter
{
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
{
var nonRequiredMYPropertyAPIs = swaggerDoc.Paths
.Where(x => !x.Key.ToLower().Contains("v1") /*the version you want to remove the property */)
.ToList();
nonRequiredMYPropertyAPIs.ForEach(x => { 
swaggerDoc.Components.Schemas["YOUR_CLASS_MODEL"]
.Properties.Remove("PROPERTY_NAME_YOU_WANT_TO_IGNORE");
});
}
}

不要忘记注册过滤器:

c.DocumentFilter<CustomSwaggerFilter>();

最新更新