Search code examples
c#swaggerasp.net-core-webapiopenapi

Swagger Fail to Generate Document When UsingAllOf


I'm using ASP.NET Core 8 Web API and Swagger.

When I try to use UseAllOfForInheritance to generate code with allOf, using the following code for building swagger:

builder.Services.AddSwaggerGen(
        (opt) =>
        {
            opt.SupportNonNullableReferenceTypes();

            opt.UseAllOfForInheritance();
            opt.SelectDiscriminatorNameUsing(type => type.Name);
})

It shows me an error which says it was expecting an enum value even thought there's no enum in the request or its response which swagger was trying to generate elements for.

System.ArgumentException: Type provided must be an Enum. (Parameter 'enumType')

How can I trace this to know what's causing it? The exception doesn't tell me the property name or any description of what it's trying to generate except for the class full name.

Sample of DTOs I'm trying to generate swagger document for:

public class SeriesBase
{
    public long Id { get; set; }

    // DX: Index
    public required string Name { get; set; }

    public long? CategoryId { get; set; }
}

public class SeriesTable : SeriesBase, ITrackCreate, ITrackUpdate
{
    #region ITrack Members

    public DateTime CreatedAt { get; set; } = UtcNow;
    public DateTime UpdatedAt { get; set; } = UtcNow;

    #endregion
}

I Solved it, thanks to Jason.

I found that I was having a generic class which accepts only enum and that's what caused the issues.

So the exact solution was this:

builder.Services.AddSwaggerGen(c =>
{
    c.SupportNonNullableReferenceTypes();
    c.UseAllOfForInheritance();
    c.SelectDiscriminatorNameUsing(type => type.Name); // optional
    c.SelectSubTypesUsing(baseType =>
    {
        return typeof(Program).Assembly.GetTypes().Where(type => !type.IsGeneric && type.BaseType != typeof(Enum) && type.IsSubclassOf(baseType));
    });
});

Solution

  • I can generate the document successfully by using below code. And if you have any concerns about this issue, you can check the official link.

    builder.Services.AddSwaggerGen(c =>
    {
        c.SupportNonNullableReferenceTypes();
        c.UseAllOfForInheritance();
        c.SelectDiscriminatorNameUsing(type => type.Name);
        c.SelectSubTypesUsing(baseType =>
        {
            return typeof(Program).Assembly.GetTypes().Where(type => type.IsSubclassOf(baseType));
        });
    });
    

    Test Result

    enter image description here