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

如何在Swagger中为条件必填可空字段标注nullable: true属性

解决Swagger条件必填可空字段标注nullable: true的方案

核心思路

Swagger原生不识别自定义的RequiredIfAttribute特性,[JsonProperty(Required = Required.AllowNull)]仅支持全局必填场景,无法匹配条件必填逻辑,因此通过自定义ISchemaFilter实现规则适配是最优方案。

实现步骤

  1. 自定义SchemaFilter类,遍历属性匹配自定义条件必填特性,对符合要求的可空属性设置Nullable标记:
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Reflection;

public class RequiredIfNullableSchemaFilter : ISchemaFilter
{
    public void Apply(OpenApiSchema schema, SchemaFilterContext context)
    {
        if (schema.Properties == null) return;

        foreach (var propertyInfo in context.Type.GetProperties())
        {
            // 匹配自定义RequiredIf特性
            var requiredIfAttr = propertyInfo.GetCustomAttribute<RequiredIfAttribute>();
            if (requiredIfAttr == null) continue;

            // 转换为Swagger默认驼峰命名的属性名,若自定义了命名规则此处同步调整
            var schemaPropertyName = char.ToLowerInvariant(propertyInfo.Name[0]) + propertyInfo.Name[1..];
            if (!schema.Properties.TryGetValue(schemaPropertyName, out var propertySchema)) continue;

            // 识别可空类型(含可空枚举),设置nullable: true
            if (Nullable.GetUnderlyingType(propertyInfo.PropertyType) != null)
            {
                propertySchema.Nullable = true;
            }

            // 可选扩展:将条件必填规则写入字段描述,提升可读性
            propertySchema.Description += $" 条件必填:当{nameof(requiredIfAttr.IdentificationType)}等于{requiredIfAttr.TargetValue}时必填,允许传null值";
        }
    }
}
  1. 在Swagger配置中注册实现的SchemaFilter
    .NET 6+ 版本在Program.cs中添加:
builder.Services.AddSwaggerGen(options =>
{
    // 保留原有Swagger配置
    options.SchemaFilter<RequiredIfNullableSchemaFilter>();
});

.NET 5及更早版本在Startup.cs的ConfigureServices方法中添加对应注册逻辑即可。

验证

启动项目后打开Swagger页面,对应字段的Schema配置就会出现nullable: true标记,和预期示例效果一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 20:45:05