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

使用System.Text.Json时Swagger不显示Fluent Validation必填字段

解决System.Text.Json下Swagger不显示Fluent Validation必填规则的问题

问题原因

Fluent Validation默认不会自动将验证规则同步到System.Text.Json对应的Swagger Schema中,而Newtonsoft JSON.NET的整合逻辑已经默认处理了这部分,所以换用System.Text.Json后需要手动添加Schema过滤器来实现规则同步。

解决步骤

  1. 确认安装必要的NuGet包
    确保项目中已安装以下匹配ASP.NET Core 7版本的包:

    • FluentValidation.AspNetCore
    • Swashbuckle.AspNetCore
  2. 创建自定义Swagger Schema过滤器
    添加一个实现ISchemaFilter接口的类,用来读取Fluent Validation规则并更新Swagger的Schema定义:

    using FluentValidation;
    using Microsoft.OpenApi.Models;
    using Swashbuckle.AspNetCore.SwaggerGen;
    
    public class FluentValidationSchemaFilter : ISchemaFilter
    {
        private readonly IValidatorFactory _validatorFactory;
    
        public FluentValidationSchemaFilter(IValidatorFactory validatorFactory)
        {
            _validatorFactory = validatorFactory;
        }
    
        public void Apply(OpenApiSchema schema, SchemaFilterContext context)
        {
            var validator = _validatorFactory.GetValidator(context.Type);
            if (validator == null) return;
    
            // 处理必填字段规则
            var rules = validator.CreateDescriptor().GetRulesForMember();
            foreach (var rule in rules)
            {
                if (rule.PropertyName == null || !schema.Properties.TryGetValue(rule.PropertyName, out var propertySchema))
                    continue;
    
                // 检查是否有NotNull/NotEmpty规则,标记为必填
                if (rule.ValidationRules.Any(r => r is FluentValidation.Validators.NotNullValidator || r is FluentValidation.Validators.NotEmptyValidator))
                {
                    schema.Required ??= new HashSet<string>();
                    schema.Required.Add(rule.PropertyName);
                }
    
                // 可扩展:添加其他规则(如长度、格式等)到Schema约束中
                // 示例:处理字符串长度规则
                // var lengthRule = rule.ValidationRules.OfType<FluentValidation.Validators.LengthValidator>().FirstOrDefault();
                // if (lengthRule != null)
                // {
                //     propertySchema.MinLength = lengthRule.Min;
                //     propertySchema.MaxLength = lengthRule.Max;
                // }
            }
        }
    }
    
  3. 配置Swagger和Fluent Validation
    在Program.cs中更新服务配置:

    var builder = WebApplication.CreateBuilder(args);
    
    // 添加Fluent Validation自动验证,扫描程序集内的验证器
    builder.Services.AddFluentValidationAutoValidation()
                    .AddFluentValidationClientsideAdapters()
                    .AddValidatorsFromAssemblyContaining<YourModelValidator>(); // 替换为你的验证器所在程序集
    
    // 配置Swagger并注册自定义Schema过滤器
    builder.Services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "你的API名称", Version = "v1" });
        c.SchemaFilter<FluentValidationSchemaFilter>();
    });
    
    // 其他服务配置...
    
    var app = builder.Build();
    
    // 启用Swagger UI
    if (app.Environment.IsDevelopment())
    {
        app.UseSwagger();
        app.UseSwaggerUI();
    }
    
    // 其他中间件配置...
    
    app.Run();
    

验证效果

重启项目后打开Swagger UI,检查模型的必填字段是否已标记为*,且Schema的required数组中包含对应字段名。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 06:52:24