FluentValidation : https://github.com/JeremySkinner/FluentValidation
关于为何要使用,因为微软自带的模型验证有点弱,还需要自己去写一大堆的验证。
关于asp.net core的集成 我用的是 FluentValidation.AspNetCore nuget
直接在addmvc后添加 AddFluentValidation() 就好了
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1).AddFluentValidation();
我一般用反射注入msdi
// 注册 Validator var types = assembly.GetTypes().Where(p => p.BaseType != null && p.BaseType.GetInterfaces().Any(x => x == typeof(IValidator))); foreach (var type in types) { if (type.BaseType != null) { var genericType = typeof(IValidator<>).MakeGenericType(type.BaseType.GenericTypeArguments[0]); services.AddTransient(genericType, type); } }
然后这里例举一些比较常用的方法
以下是我的模型 。
public class UserInput { public string CustomerId { get; set; } public string UserName { get; set; } public string PhoneNumber { get; set; } public string FullName { get; set; } public string Description { get; set; } public string UnionId { get; set; } public string Email { get; set; } public string Password { get; set; } }
这里是我的validator
public class UserInputVaildator : AbstractValidator<UserInput> { public UserInputVaildator() { RuleFor(m => m.UserName).NotEmpty().WithMessage("登录名是必须的"); RuleFor(m => m.CustomerId).NotEmpty().WithMessage("客户Id是必须的"); //当手机号为空的时候就不会再去验证手机号格式是否 因为默认是不会停止验证。 RuleFor(m => m.PhoneNumber) .Cascade(CascadeMode.StopOnFirstFailure) .NotEmpty().WithMessage("手机号是必须的") .PhoneNumber().WithMessage("手机格式不正确"); //这里的意思是当 邮箱不为空时采取验证邮箱格式是否正确 RuleFor(m => m.Email) .EmailAddress().When(m => !string.IsNullOrWhiteSpace(m.Email)).WithMessage("邮箱格式不正确"); } }
当然,还有一些其他的东西
public class TestInput { public string Grant { get; set; } public int Number { get; set; } }
public class TestInputValidator : AbstractValidator<TestInput> { public TestInputValidator() {
RuleSet("test", () => { RuleFor(m => m.Number).GreaterThan(0).WithMessage("Number要大于0"); }); RuleFor(m => m.Grant).NotEmpty().WithMessage("Grant不能为空"); } }
规则的设置,可以适应不同的验证场景,对同一个Model进行不同的验证
[Route("api/[controller]")] [ApiController] public class TestController : ControllerBase { // [HttpGet] public IActionResult Get([FromQuery]TestInput input) { return Ok(); } //规则的设置,可以适应不同的验证场景,对同一个Model进行不同的验证 [HttpPost] public IActionResult Index([FromBody][CustomizeValidator(RuleSet = "test")]TestInput input) { return Ok("213"); } }
父类,接口的验证
public class CustomerCreateInput : ClientInput, ICustomerInput{ //具体的实现接口 } public class CustomerInputInterfaceValidator : AbstractValidator<ICustomerInput>{ //具体 接口 验证逻辑 } public class ClientInputVaildators : AbstractValidator<ClientInput>{ //集体 基类 验证逻辑 } //那么我该如果重用接口和基类的验证逻辑 public class CustomerCreateInputValidator : AbstractValidator<CustomerCreateInput> { public CustomerCreateInputValidator() { //只需要包含进来 Include(new CustomerInputInterfaceValidator()); Include(new ClientInputVaildators()); } }
这里就有个问题,如果包含的验证类中包含了 RuleSet,那么该如何启用。因为默认不会启用,这个问题,我也不知道 (~ ̄▽ ̄)~ 只能说我也不太精通,昨天刚刚开始用。