Swashbuckle generates schemas for internal c# classes

Viewed 254

When using Swashbuckle.AspNetCore (version 6.3.1) with System.text.json, the schemas generate a bunch of internals from c#, like a schema for Assembly, ConstructorInfo, and others.

I think this happens when I've created an endpoint that returns an interface (possibly). Not entirely sure. If I utilize the Swashbuckle.AspNetCore.Newtonsoft package for generating the swagger documentation it isn't a problem - these schemas are not generated. I'd however like to not have a dependency on newtonsoft for the sole reason of getting the valid schemas.

It's not a huge issue, however it is a bit annoying that our openapi/swagger docs have irrelevant information. I'd love to get around that.

Is this a known bug? Is there a way around it? Any help would be much appreciated.

I've tried to search for different combinations of the problem, but with no success. My querying skills my be bad, so if this question has already been asked, then I am truly sorry.

image of schemas that contain both Assembly, CallingConventions and ContructorInfo

EDIT: The bug seems to be due to the fact that we have a value type that we expose in the API with a custom serializer. that object has a Type property, however, this is never actually exposed in the API due to the serializer - (which we also registered with Swashbuckle, so it isn't actually exposed in the Swashbuckle documentation, however, I assume Swashbuckle already added the objects to the schema prior to us registering the "correct" serializer.)

1 Answers

One way to remove it is by an IDocumentFilter like this:


    public class RemoveSchemasFilter : IDocumentFilter
    {
        public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
        {
            var types = (Assembly.GetAssembly(this.GetType())).GetTypes().Where(x => x.IsClass).Select(x => x.Name);

            IDictionary<string, OpenApiSchema> _remove = swaggerDoc.Components.Schemas.Where(x => !types.Contains(x.Key)).ToDictionary(x => x.Key, x => x.Value);
            foreach (KeyValuePair<string, OpenApiSchema> _item in _remove)
            {
                swaggerDoc.Components.Schemas.Remove(_item.Key);
            }
        }
    }

in you DI where you register swagger just add this

builder.Services.AddSwaggerGen(c => c.DocumentFilter<RemoveSchemasFilter>())
Related