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

升级至FluentValidation.AspNetCore 11.2后如何配置自定义PropertyNameResolver

升级至FluentValidation.AspNetCore 11.2后配置自定义PropertyNameResolver的方法

FluentValidation 11.x版本对全局配置逻辑做了调整,结合AspNetCore集成特性,你可以按以下步骤配置驼峰式属性名称:

正确的全局配置方式

确保在注册FluentValidation服务时,通过ValidatorOptions.Global设置PropertyNameResolver,配置时机需在验证器注册前或AddFluentValidation的配置委托内完成:

builder.Services.AddFluentValidation(fv =>
{
    // 配置全局属性名称解析器为驼峰式
    ValidatorOptions.Global.PropertyNameResolver = (type, memberInfo, expression) =>
    {
        if (memberInfo == null) return null;
        // 首字母小写实现驼峰格式
        return char.ToLowerInvariant(memberInfo.Name[0]) + memberInfo.Name.Substring(1);
    };

    // 注册你的验证器(示例:从包含指定验证器的程序集注册)
    fv.RegisterValidatorsFromAssemblyContaining<YourValidator>();
});

确保AspNetCore使用FluentValidation的验证结果

如果配置后仍不生效,大概率是AspNetCore默认模型验证逻辑干扰了结果,需禁用默认验证响应,让FluentValidation全权处理:

builder.Services.Configure<ApiBehaviorOptions>(options =>
{
    // 关闭AspNetCore自带的模型验证错误过滤器
    options.SuppressModelStateInvalidFilter = true;
});

之前尝试失效的原因

  • 直接设置ValidatorOptions.Global.PropertyNameResolver若时机错误(比如在验证器注册完成后配置),无法覆盖已注册验证器的配置。
  • 使用Configure<ValidatorConfiguration>是错误路径,11.x版本中FluentValidation全局配置统一通过ValidatorOptions.Global访问,不存在ValidatorConfiguration这个配置类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 03:01:00