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

如何在Swagger文档中为Enum类型响应字段指定自定义示例值?

问题

定义了NotFoundResponse类作为记录未找到时的响应模型,其中ErrorCode字段通过XML注释标记了<example>RecordNotFound</example>,但Swagger的示例响应始终显示枚举的第一个值None,而非指定的RecordNotFound。

相关代码

NotFoundResponse类

public class NotFoundResponse
{
    /// <example>RecordNotFound</example>
    public ErrorCodes ErrorCode { get; set; }

    /// <example>5</example>
    public int NumericErrorCode { get; set; }

    /// <example>A random error message.</example>
    public string ErrorMessage { get; set; }
}

ErrorCodes枚举

public enum ErrorCodes
{
    None = 0,
    // 其他枚举成员
    RecordNotFound = 5
}

解决方案

方法1:使用示例提供器指定响应(推荐)

通过Swashbuckle.AspNetCore.Filters包提供的IExamplesProvider接口,为响应模型生成指定的示例值,强制Swagger显示目标枚举:

// 先安装Swashbuckle.AspNetCore.Filters包
// 定义示例类
public class NotFoundResponseExample : IExamplesProvider<NotFoundResponse>
{
    public NotFoundResponse GetExamples()
    {
        return new NotFoundResponse
        {
            ErrorCode = ErrorCodes.RecordNotFound,
            NumericErrorCode = 5,
            ErrorMessage = "A random error message."
        };
    }
}

// 在接口方法上绑定示例
[HttpGet("{id}")]
[SwaggerResponse(StatusCodes.Status404NotFound, Type = typeof(NotFoundResponse), Example = typeof(NotFoundResponseExample))]
public IActionResult Get(int id)
{
    // 业务逻辑
    return NotFound(new NotFoundResponse 
    { 
        ErrorCode = ErrorCodes.RecordNotFound, 
        NumericErrorCode = 5, 
        ErrorMessage = "指定记录不存在" 
    });
}

方法2:自定义Schema过滤器

编写过滤器直接修改Swagger的Schema配置,为指定字段设置枚举示例:

public class EnumExampleFilter : ISchemaFilter
{
    public void Apply(OpenApiSchema schema, SchemaFilterContext context)
    {
        // 定位到NotFoundResponse的ErrorCode字段
        if (context.Type == typeof(NotFoundResponse) && schema.Properties.TryGetValue("errorCode", out var errorCodeProp))
        {
            errorCodeProp.Example = new OpenApiString("RecordNotFound");
        }
    }
}

// 在Swagger配置中注册过滤器
builder.Services.AddSwaggerGen(c =>
{
    c.SchemaFilter<EnumExampleFilter>();
    // 其他Swagger配置...
});

方法3:调整枚举定义(不推荐)

若不想引入额外依赖,可临时调整枚举成员顺序,把目标枚举设为第一个成员,但此方式可能影响业务逻辑中枚举的默认值行为,需谨慎使用:

public enum ErrorCodes
{
    RecordNotFound = 5,
    None = 0,
    // 其他枚举成员
}

方法4:强化XML注释配置

确保项目已启用XML文档生成,且Swagger已加载注释文件,同时在枚举成员上补充注释:

public enum ErrorCodes
{
    None = 0,
    /// <summary>记录未找到错误码</summary>
    RecordNotFound = 5
}

public class NotFoundResponse
{
    /// <summary>错误类型枚举</summary>
    /// <example>RecordNotFound</example>
    public ErrorCodes ErrorCode { get; set; }
    // 其他字段...
}

// Swagger配置中启用XML注释
builder.Services.AddSwaggerGen(c =>
{
    var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
    c.IncludeXmlComments(xmlPath);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 14:28:00