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

FluentValidation规则未同步到Swagger Schema的问题求助

问题:FluentValidation规则无法通过MicroElements库在Swagger中显示

我遇到了FluentValidation规则无法通过MicroElements库在Swagger Schema中显示的问题,调整AddFluentValidationRulesToSwagger的调用顺序也无效果,查阅相关文档未找到有效解决方案,想确认哪里配置错误。

以下是我的配置:

Program.cs代码

builder.Services.AddHttpContextAccessor();

builder.Services.AddControllers(opt =>
{
    opt.Filters.Add(new AppExceptionInterceptorAsync());
});

builder.Services.AddEndpointsApiExplorer();

builder.Services.AddValidatorsFromAssemblyContaining<Program>(lifetime: ServiceLifetime.Transient);
builder.Services.AddFluentValidationRulesToSwagger();

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "You api title", Version = "v1" });
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

实体类与验证器代码

public class LoginInputDto
{
    public string Email { get; set; } = string.Empty;
    public string Password { get; set; } = string.Empty;
}

public class LoginInputDtoValidator : AbstractValidator<LoginInputDto>
{
    public LoginInputDtoValidator()
    {
        RuleFor(c => c.Email)
            .EmailAddress()
            .WithMessage("E-mail inválido");

        RuleFor(c => c.Email)
            .NotEmpty()
            .WithMessage("Email deve ser preenchido");

        RuleFor(c => c.Email)
            .NotNull()
            .WithMessage("Email deve ser preenchido");

        RuleFor(c => c.Password)
            .NotEmpty()
            .WithMessage("Senha deve ser preenchido");
    }
}

已安装的NuGet包

  • FluentValidation Version="11.5.2"
  • FluentValidation.DependencyInjectionExtensions Version="11.5.2"
  • MicroElements.Swashbuckle.FluentValidation Version="5.7.0"
  • Microsoft.AspNetCore.OpenApi Version="7.0.4"
  • Swashbuckle.AspNetCore Version="6.4.0"
  • Swashbuckle.AspNetCore.Newtonsoft Version="6.5.0"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 01:27:45