FluentValidation在asp.net core中怎么使用?
先安装包。
Install-Package FluentValidation.AspNetCore
和上一篇的实体类和验证类一样。
实体类:
public class Person { public int Id { get; set; } public string Name { get; set; } public string Tel { get; set; } public string Email { get; set; } public DateTime Birthday { get; set; } public string IDCard { get; set; } public PersonAddress Address { get; set; } } public class PersonAddress { public string Country { get; set; } public string Province { get; set; } public string City { get; set; } public string County { get; set; } public string Address { get; set; } public string Postcode { get; set; } }
验证类:
/// <summary> /// Person验证 /// </summary> public class PersonValidator : AbstractValidator<Person> { public PersonValidator() { RuleFor(p => p.Name).NotNull().NotEmpty(); RuleFor(p => p.Email).NotNull().EmailAddress(); RuleFor(p => p.Birthday).NotNull(); RuleFor(p => p.IDCard) .NotNull() .When(p => (DateTime.Now > p.Birthday.AddYears(1))) .WithMessage(p => $"出生日期为{p.Birthday},现在时间为{DateTime.Now},大于一岁,CardID值必填!") .NotEmpty() .When(p => (DateTime.Now > p.Birthday.AddYears(1))) .WithMessage(p => $"出生日期为{p.Birthday},现在时间为{DateTime.Now},大于一岁,CardID值必填!") .Length(18) .When(p => (DateTime.Now > p.Birthday.AddYears(1))); RuleFor(p => p.Tel).NotNull().Matches(@"^(\d{3,4}-)?\d{6,8}$|^[1]+[3,4,5,8]+\d{9}$"); RuleFor(p => p.Address).NotNull(); RuleFor(p => p.Address).SetValidator(new PersonAddressValidator()); } } /// <summary> /// Person Address验证 /// </summary> public class PersonAddressValidator : AbstractValidator<PersonAddress> { public PersonAddressValidator() { RuleFor(a => a.Country).NotNull().NotEmpty(); RuleFor(a => a.Province).NotNull().NotEmpty(); RuleFor(a => a.City).NotNull().NotEmpty(); RuleFor(a => a.County).NotNull().NotEmpty(); RuleFor(a => a.Address).NotNull().NotEmpty(); RuleFor(a => a.Postcode).NotNull().NotEmpty().Length(6); } }
Starup.cs
public void ConfigureServices(IServiceCollection services) { services .AddControllers() .AddFluentValidation(); services.AddTransient<IValidator<Person>, PersonValidator>(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "FluentValidationWebDemo01", Version = "v1" }); }); }
这里和asp.net core mvc的模型验证如出一辙。
[ApiController] [Route("[controller]")] public class HomeController : ControllerBase { private readonly ILogger<HomeController> _logger; private readonly IValidator<Person> _validator; public HomeController(ILogger<HomeController> logger, IValidator<Person> validator) { _validator = validator; _logger = logger; } [HttpPost("/addperson")] public IActionResult AddPerson([FromBody] Person person) { _logger.LogInformation("添加Person"); if (ModelState.IsValid) { return Ok("验证成功后,假装这里作了后端业务处理"); } _logger.LogError("验证Person失败"); return BadRequest("person没有验证通过"); } }
测试传入数据:
{ "id":0, "birthday":"2021-03-29T07:00:18.061Z", "idCard":"", "name":"", "email":"axzxs2001163.com", "tel":"1345346714", "address":{ "country":"中国", "province":"山西", "city":"", "county":"古城", "address":"", "postcode":"04600" } }
结果:
{ "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1", "title": "One or more validation errors occurred.", "status": 400, "traceId": "00-21fffead3f693fdf9156d796baf4e4ef-a7d39f85acf57cff-00", "errors": { "Tel": [ "'Tel' 的格式不正确。" ], "Name": [ "'Name' 不能为空。" ], "Email": [ "'Email' 不是有效的电子邮件地址。" ], "Address.City": [ "'City' 不能为空。" ], "Address.Address": [ "'Address' 不能为空。" ], "Address.Postcode": [ "'Postcode' 必须是 6 个字符,您输入了 5 字符。" ] } }
还是那句话,FluentValidation提供了更灵活,完强大的验证方式
想要更快更方便的了解相关知识,可以关注微信公众号