You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core 8中使用UseAllOfForInheritance生成Swagger文档报错

问题:ASP.NET Core 8 Web API Swagger配置UseAllOfForInheritance时抛出枚举类型错误

我正在使用ASP.NET Core 8 Web API和Swagger,尝试通过UseAllOfForInheritance生成包含allOf结构的API文档,配置代码如下:

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

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

运行时抛出以下错误:

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

当前需要生成文档的请求和响应中并未包含枚举类型,且异常未提供具体属性名称等排查信息,该如何追踪问题原因?以下是待生成文档的DTO示例:

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
}

问题原因与解决方法

问题根源是项目中存在仅接受枚举的泛型类,导致Swagger在扫描继承关系时误将枚举相关类型纳入处理。通过自定义子类型筛选逻辑,排除泛型类和枚举类型,即可解决该问题,修改后的Swagger配置代码如下:

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

内容的提问来源于stack exchange,提问作者Adnan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 18:13:12