Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove internal types from swagger #1633

Merged
merged 1 commit into from
Jan 17, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
using System.Reflection;
using Asp.Versioning.ApiExplorer;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Interfaces;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace OutOfSchool.WebApi.Extensions.Startup;

Expand All @@ -26,6 +29,7 @@ public static IServiceCollection AddSwagger(this IServiceCollection services, Sw
// Set the comments path for the Swagger JSON and UI.
c.IncludeXmlComments(XmlCommentsFilePath);

c.SchemaFilter<ExcludeClrTypesFilter>(new List<Assembly> {typeof(OutOfSchoolDbContext).Assembly});
c.DocumentFilter<SwaggerFeatureGateFilter>();
c.OperationFilter<AuthorizeCheckOperationFilter>();
c.AddSecurityDefinition(config.SecurityDefinitions.Title, new OpenApiSecurityScheme
Expand Down Expand Up @@ -82,4 +86,30 @@ public static IApplicationBuilder UseSwaggerWithVersioning(

return app;
}

private class ExcludeClrTypesFilter(List<Assembly> assemblies) : ISchemaFilter
{
private List<string> blacklist = assemblies.SelectMany(assembly => assembly.GetTypes())
.Where(t => !t.FullName.Contains("Enums")).Select(t => t.Name).ToList();

public void Apply(OpenApiSchema schema, SchemaFilterContext context)
{
if (schema.Properties != null)
{
foreach (var prop in schema.Properties)
{
if (prop.Value.Reference != null
&& blacklist.Contains(prop.Value.Reference.Id))
{
prop.Value.Reference = null;
}
}
}

foreach (var key in blacklist)
{
context.SchemaRepository.Schemas.Remove(key);
}
}
}
}
Loading