如何将FluentValidation自定义消息绑定到ModelState?自定义消息未生效原因
问题描述
在使用FluentValidation创建验证器并搭配AsyncActionFilter时,传入无效值后返回的是FluentValidation默认错误消息,而非自定义消息。相关代码及返回结果如下:
AsyncActionFilter类
public class ModelValidatorFilterAttribute : IAsyncActionFilter { public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { if (!context.ModelState.IsValid) { var errorMessages = context.ModelState.Values .Select( x => new ExceptionResponse.ExceptionMessage { Message = x.Errors.First().ErrorMessage }) .ToList(); throw new ValidationException(errorMessages); } await next(); } }
验证器
public class MyValidator : AbstractValidator<MyRequestDto> { public MyValidator() { RuleFor(s => s.ProductId).NotEmpty().NotNull() .WithMessage(x => "my custom message"); } }
Startup配置
services.AddFluentValidation(); services.Configure<ApiBehaviorOptions>(options => { options.SuppressModelStateInvalidFilter = true; });
返回结果
{ "exceptionMessages": [ { "message": "'Product Id' must not be empty.", "duration": 0, "type": "Type" } ] }
原因分析
- 验证器未被正确注册:仅调用
services.AddFluentValidation()不足以让ASP.NET Core识别自定义验证器,此时系统会使用ASP.NET Core自带的模型验证逻辑,返回默认错误消息而非FluentValidation的自定义消息。 - 重复验证规则冗余:
NotEmpty()规则已包含NotNull()的检查逻辑(针对字符串、集合等类型),重复添加NotNull()属于冗余配置,虽不会直接导致默认消息,但可能影响规则执行优先级。
解决方案
1. 正确注册FluentValidation验证器
在Startup的服务配置中添加验证器注册逻辑,二选一即可:
- 手动注册单个验证器:
services.AddScoped<IValidator<MyRequestDto>, MyValidator>(); - 自动扫描程序集内所有验证器(推荐,适合多验证器场景):
services.AddFluentValidation(fv => { fv.RegisterValidatorsFromAssemblyContaining<MyValidator>(); });
2. 优化验证规则
移除冗余的NotNull()规则,简化验证逻辑:
public class MyValidator : AbstractValidator<MyRequestDto> { public MyValidator() { RuleFor(s => s.ProductId).NotEmpty() .WithMessage(x => "my custom message"); } }
3. 确保过滤器生效
确认ModelValidatorFilterAttribute已正确应用:
- 通过特性标记在控制器/动作上:
[ServiceFilter(typeof(ModelValidatorFilterAttribute))] - 或全局注册过滤器:
services.AddControllers(options => { options.Filters.Add<ModelValidatorFilterAttribute>(); });
完成以上配置后,FluentValidation会接管模型验证流程,无效值触发验证时将返回自定义消息。
内容的提问来源于stack exchange,提问作者Fatih
相关产品推荐
相关产品推荐

