Search code examples
c#swaggerswagger-uiswashbuckle

Swagger naming issue with generics


I want swagger to generate models seperately for generic sub models as shown in the example below:

public class TheModel<T>
{
    public IEnumerable<T> GenericModel { get; set; }
}

public class GenericModel
{
}

public class AnotherGenericModel
{
}

Swagger generates the following schemas:

  • GenericModel
  • GenericModelTheModel
  • AnotherGenericModel
  • AnotherGenericModelTheModel

What I want the schemas to be:

  • GenericModel
  • TheModel<GenericModel>
  • AnotherGenericModel
  • TheModel<AnotherGenericModel>

I want to change the schemas created changed to the expected schemas.
Can this be done with Swashbuckle?


Solution

  • I have solved my own question and came up with the following solution shown below:

    public class GenericFilter : ISchemaFilter
    {
        public void Apply(OpenApiSchema schema, SchemaFilterContext context)
        {
            var type = context.Type;
    
            if (type.IsGenericType == false)
                return;
    
            schema.Title = $"{type.Name[0..^2]}<{type.GenericTypeArguments[0].Name}>";
        }
    }
    

    And add this to the Startup.cs SwaggerGenOptions

    options.SchemaFilter<GenericFilter>();