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

如何使用Fluent Validation验证可空枚举列表的有效值?

实现可空枚举列表的条件验证(Fluent Validation)

要实现仅当employeeTypes不为null时才验证其中枚举值有效性的需求,你可以通过Fluent Validation的When条件约束结合列表元素验证来完成,以下是具体步骤和代码示例:

1. (可选但推荐)封装请求模型

将Action参数封装为模型类,更符合ASP.NET Core的验证规范:

public enum EmployeeType
{
    LEVEL_1 = 1,
    LEVEL_2 = 2,
    LEVEL_3 = 3,
    LEVEL_4 = 4
}

public class GetEmployeesRequest
{
    public List<EmployeeType>? EmployeeTypes { get; set; }
}

2. 创建Fluent Validation验证器

编写验证器类,使用When指定触发验证的条件,同时验证列表中的每个枚举值:

方式一:批量验证(返回统一错误)

适合只需要提示存在无效值的场景:

using FluentValidation;

public class GetEmployeesRequestValidator : AbstractValidator<GetEmployeesRequest>
{
    public GetEmployeesRequestValidator()
    {
        // 仅当EmployeeTypes不为null时,验证所有元素都是有效的枚举值
        RuleFor(x => x.EmployeeTypes)
            .Must(types => types.All(Enum.IsDefined))
            .WithMessage("employeeTypes参数包含无效值")
            .When(x => x.EmployeeTypes != null);
    }
}

方式二:逐个验证(返回具体错误)

需要明确指出哪个枚举值无效时,使用RuleForEach:

using FluentValidation;

public class GetEmployeesRequestValidator : AbstractValidator<GetEmployeesRequest>
{
    public GetEmployeesRequestValidator()
    {
        // 仅当EmployeeTypes不为null时,逐个验证每个元素是有效的枚举值
        RuleForEach(x => x.EmployeeTypes)
            .IsInEnum()
            .WithMessage("员工类型 {PropertyValue} 不是有效选项")
            .When(x => x.EmployeeTypes != null);
    }
}

3. 在Action中使用验证器

手动验证方式

在Controller中注入验证器,手动执行验证逻辑:

private readonly IValidator<GetEmployeesRequest> _validator;
private readonly IEmployeeEngine _engine;

// 构造函数注入依赖
public EmployeesController(IValidator<GetEmployeesRequest> validator, IEmployeeEngine engine)
{
    _validator = validator;
    _engine = engine;
}

public async Task<IActionResult> GetEmployeesAsync([FromQuery] GetEmployeesRequest request)
{
    var validationResult = await _validator.ValidateAsync(request);
    if (!validationResult.IsValid)
    {
        return BadRequest(validationResult.Errors);
    }
   
    var employees = await _engine.GetEmployes(request.EmployeeTypes);
    return Ok(employees);
}

自动验证方式(更简洁)

在Program.cs中配置Fluent Validation自动验证,无需手动调用验证方法:

var builder = WebApplication.CreateBuilder(args);

// 添加Fluent Validation自动验证
builder.Services.AddFluentValidationAutoValidation();
// 扫描程序集中的所有验证器
builder.Services.AddValidatorsFromAssemblyContaining<GetEmployeesRequestValidator>();

// 其他服务配置...

配置完成后,Action只需接收模型参数,框架会自动执行验证并返回错误:

public async Task<IActionResult> GetEmployeesAsync([FromQuery] GetEmployeesRequest request)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }
   
    var employees = await _engine.GetEmployes(request.EmployeeTypes);
    return Ok(employees);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 00:55:12