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

报错:'ValidatorAttribute'无接受1个参数的构造函数,求解特性问题

解决'ValidatorAttribute'不包含带1个参数的构造函数问题

问题原因

你遇到的错误是因为使用的FluentValidation版本为10.0及以上,主包FluentValidation中已移除了带单个Type参数的ValidatorAttribute构造函数;或是未正确引用包含该特性的包。

解决方案

方案1:改用FluentValidation.AspNetCore包的特性

  • 先安装FluentValidation.AspNetCore NuGet包
  • 修正代码中的特性引用,添加对应命名空间后使用:
    using FluentValidation.AspNetCore; // 添加此命名空间引用
    using MVC_Kutuphane_Otomasyonu.Entities.Validations;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace MVC_Kutuphane_Otomasyonu.Entities.Model
    {
        [ValidatorAttribute(typeof(DuyurularValidator))]
        public class Duyurular
        {
            public int Id { get; set; }
            public string Baslik { get; set; }
            public string Duyuru { get; set; }
            public string Aciklama { get; set;}
            public DateTime Tarih { get; set; }
        }
    }
    

方案2:降级FluentValidation到9.x版本

卸载当前版本的FluentValidation,安装9.x系列的稳定版本(如9.5.4),即可继续使用原有的[Validator(typeof(DuyurularValidator))]写法。

方案3:推荐通过启动配置注册验证器(更灵活)

放弃特性标记,在项目启动文件(.NET 6+为Program.cs,旧版为Startup.cs)中批量注册验证器:

// Program.cs示例(.NET 6+)
builder.Services.AddControllersWithViews()
    .AddFluentValidation(fv => 
        fv.RegisterValidatorsFromAssemblyContaining<DuyurularValidator>()
    );

这种方式无需依赖特性,也能避免版本更新带来的兼容性问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 02:32:56