Skip to content

Instantly share code, notes, and snippets.

@scottoffen
Last active October 2, 2023 22:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scottoffen/d485202f31eb4213082bc43b42803cca to your computer and use it in GitHub Desktop.
Save scottoffen/d485202f31eb4213082bc43b42803cca to your computer and use it in GitHub Desktop.
Swagger Exclude in ASP.NET 6.0
builder.Services.AddSwaggerGen(options =>
{
options.SchemaFilter<SwaggerExcludeFilter>();
options.DocumentFilter<SwaggerExcludeFilter>();
});
using System;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Enum | AttributeTargets.Field | AttributeTargets.Property)]
public class SwaggerExcludeAttribute : Attribute { }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
public class SwaggerExcludeFilter : ISchemaFilter, IDocumentFilter
{
private static HashSet<string> ExcludedKeys = new();
public void Apply(OpenApiSchema schema, SchemaFilterContext context)
{
if (context.Type.GetCustomAttribute<SwaggerExcludeAttribute>() != null)
{
ExcludedKeys.Add(context.Type.FullName);
return;
}
if (schema.Properties != null)
{
var excludedProperties = context.Type.GetProperties().Where(t => t.GetCustomAttribute<SwaggerExcludeAttribute>() != 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);
}
}
}
if (context.Type.IsEnum || (Nullable.GetUnderlyingType(context.Type)?.IsEnum ?? false))
{
var type = (context.Type.IsEnum)
? context.Type
: Nullable.GetUnderlyingType(context.Type);
var enums = new List<IOpenApiAny>();
foreach (var name in Enum.GetNames(type))
{
var value = type.GetMember(name)[0];
if (!value.GetCustomAttributes<SwaggerExcludeAttribute>().Any())
{
enums.Add(new OpenApiString(name));
}
}
schema.Enum = enums;
}
}
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
{
foreach (var key in swaggerDoc.Components.Schemas.Keys)
{
if (ExcludedKeys.Any(x => x.EndsWith(key)))
{
swaggerDoc.Components.Schemas.Remove(key);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment