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

.NET 10内置OpenAPI生成器如何生成可空枚举?

解决.NET 10内置OpenAPI生成器可空枚举的Schema生成问题

问题根源

.NET 10内置OpenAPI生成器默认采用OpenAPI 3.1规范的oneOf语法处理可空类型(包括可空枚举),生成的Schema会包含枚举类型和"type": "null"的组合。但部分客户端生成工具无法正确识别这种结构,转而生成无关的新类,而非预期的可空枚举类型。而Swashbuckle则是通过nullable: true标记来表示可空枚举,更符合多数客户端工具的解析逻辑。

解决方案

方案1:调整内置生成器的Schema生成选项

通过配置JsonSchemaGeneratorOptions,强制可空值类型(包括枚举)使用nullable: true标记,而非oneOf结构:

builder.Services.AddOpenApi(options =>
{
    options.SchemaGeneratorOptions = new JsonSchemaGeneratorOptions
    {
        // 启用可空引用类型的处理
        NullabilityHandling = NullabilityHandling.IncludeNullableReferenceTypes,
        // 将值类型的可空形式转换为`nullable: true`标记
        ValueTypeNullableHandling = ValueTypeNullableHandling.ConvertToNullable
    };
});

方案2:自定义Schema过滤器修正枚举Schema

如果方案1无法满足需求,可以通过自定义ISchemaFilter手动修正可空枚举的Schema:

  1. 创建过滤器类:
using System.Reflection;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;

public class NullableEnumSchemaFilter : ISchemaFilter
{
    public void Apply(OpenApiSchema schema, SchemaFilterContext context)
    {
        // 检查当前类型是否为可空枚举
        var underlyingType = Nullable.GetUnderlyingType(context.Type);
        if (underlyingType != null && underlyingType.IsEnum)
        {
            // 移除oneOf配置
            schema.OneOf = null;
            // 设置nullable标记为true
            schema.Nullable = true;
            // 引用对应的枚举Schema,避免重复定义
            schema.Reference = new OpenApiReference
            {
                Type = ReferenceType.Schema,
                Id = underlyingType.Name
            };
            // 清空当前Schema的类型定义,确保使用引用
            schema.Type = null;
            schema.Enum = null;
        }
    }
}
  1. 注册过滤器到OpenAPI生成器:
builder.Services.AddOpenApi(options =>
{
    options.SchemaGeneratorOptions.SchemaFilters.Add(new NullableEnumSchemaFilter());
});

额外注意事项

  • 确保客户端生成工具(如OpenAPI Generator、NSwag)支持解析OpenAPI规范中的nullable: true标记,以生成正确的可空枚举类型。
  • 若需使用OpenAPI 3.0规范而非3.1,可在AddOpenApi中指定版本:
options.OpenApiVersion = new Version(3, 0);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.01 13:27:30