校验机制
.Net Core内置
1、在.Net Core中内置了对数据校验的支持,在System.ComponentModel.DataAnnotations这个命名空间下有如:[Required]、[EamilAddress]、[RegularExpression]。CustomValidationAttribute、IValidatableObject。
2、内置的校验机制的问题:校验规则都是和模型类耦合在一起,违反“单一职责原则”,很多常用的校验都需要编写自定义校验规则,而且写起来麻烦。
1 2 3 4 5 6 7
| public class DataTest { [Required] public string UserName { get; set; } public string Password { get; set; } [EmailAddress] public string Email { get; set; } }
|
第三方包(FluentValidation)
1、用类似于EF Core中Fluent API的方式进行校验规则的 配置,也就是我们可以把对模型类的校验放到单独的校验类中
2、NuGet安装:
FluentValidation.AspNetCore
3、
1 2 3 4
| //Program.cs builder.Services.AddFluentValidation(opt => { opt.RegisterValidatorsFromAssembly(Assembly.GetExecutingAssembly()); });
|
1 2 3 4 5 6 7
| //请求实体类 public class AddNewUserRequest { public string UserName { get; set; } public string Password { get; set; } public string Email { get; set; } public string Password2 { get; set; } }
|
1 2 3 4 5 6 7 8
| //请求校验类 public class AddNewUserRequestValidator :AbstractValidator<AddNewUserRequest> { public AddNewUserRequestValidator() { RuleFor(x => x.Email).NotNull().EmailAddress().WithMessage("密码不合法").Must(x=>x.EndsWith("@163.com")||x.EndsWith("@qq.com")).WithMessage("只支持163或者qq邮箱"); RuleFor(x => x.UserName).NotNull().Length(6, 10); RuleFor(x => x.Password).Equal(x => x.Password2).WithMessage("两次密码不一致"); } }
|
FluentValidation支持从构造函数依赖注入。