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

Swashbuckle与.NET Core Web API:可空枚举只读Swagger Schema未在YAML生效

可空枚举Swagger只读标识缺失的解决办法

问题根源

Swashbuckle处理可空枚举(比如SampleEnum?)时,会把它包装成Nullable<SampleEnum>,默认不会把原属性上的[SwaggerSchema(ReadOnly = true)]特性同步到生成的Schema里,导致YAML里没出现只读标记,而普通字符串字段不受影响。

两种解决方式

方式一:自定义Schema过滤器(通用方案)

写一个过滤器,专门处理可空类型的特性传递:

using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.Annotations;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Reflection;

public class NullableReadOnlySchemaFilter : ISchemaFilter
{
    public void Apply(OpenApiSchema schema, SchemaFilterContext context)
    {
        // 只处理可空值类型
        if (!context.Type.IsGenericType || context.Type.GetGenericTypeDefinition() != typeof(Nullable<>))
            return;

        // 获取原属性上的SwaggerSchema特性
        var swaggerAttr = context.MemberInfo?.GetCustomAttribute<SwaggerSchemaAttribute>();
        if (swaggerAttr != null && swaggerAttr.ReadOnly)
        {
            schema.ReadOnly = true;
        }
    }
}

然后在Swagger注册时加上这个过滤器:

builder.Services.AddSwaggerGen(options =>
{
    // 你的其他Swagger配置...
    options.SchemaFilter<NullableReadOnlySchemaFilter>();
});

方式二:单个属性临时修复

如果只是个别属性有问题,可以直接在特性里显式指定类型:

[JsonPropertyName("sampleEnum")]
[SwaggerSchema(ReadOnly = true, Type = "integer")]
public SampleEnum? sampleEnum{ get; set; }

这种方式不用写过滤器,但只适合单个属性,不够通用。

验证

重新生成Swagger YAML文件,sampleEnum字段就会和name一样带上readOnly: true的标记了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 15:53:20