美文网首页
Asp.net Core添加fluent Validation

Asp.net Core添加fluent Validation

作者: 早睡使人快乐 | 来源:发表于2020-01-20 16:56 被阅读0次

nuget文档地址
通过vscode的nuget插件安装FluentValidation AspnetCore 8.6.1版本
这个版本依赖.netCore 3.0或者.netCore 2.0
修改项目的工程文件

  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
  </PropertyGroup>

改为

    <PropertyGroup>
    <TargetFramework>netcoreapp3.0</TargetFramework>
  </PropertyGroup>

同样的修改这个项目所有依赖的targetFramework
(实际过程中,我的API项目是3.0,没有修改其他的项目,不知道为什么也可以使用,求解答)


image.png

在业务逻辑中添加CommandValidator类用于验证

        public class CommandValidator : AbstractValidator<Command>
        {   
            public CommandValidator()
            {
                RuleFor(x => x.Title).NotEmpty();
                RuleFor(x => x.Description).NotEmpty();
                RuleFor(x => x.Category).NotEmpty();
                RuleFor(x => x.Date).NotEmpty();
                RuleFor(x => x.City).NotEmpty();
                RuleFor(x => x.Venue).NotEmpty();
            }
        }

添加构造函数

            services.AddControllers()
            .AddFluentValidation(cfg =>
            {
//注册业务类
                cfg.RegisterValidatorsFromAssemblyContaining<Create>();
            });

在服务中注册

相关文章

网友评论

      本文标题:Asp.net Core添加fluent Validation

      本文链接:https://www.haomeiwen.com/subject/pfvjzctx.html