作者: Anthony Giretti
译者: Lamond Lu
介绍
验证用户输入是一个 web 应用中的基本功能. 对于生产系统, 开发人员通常需要花费大量时间, 编写大量的代码来完成这一功能. 如果我们使用 FluentValidation 构建 ASP.NET Core Web API, 输入验证的任务将比以前容易的多.
FluentValidation 是一个非常流行的构建强类型验证规则的. NET 库.
配置项目
第一步: 下载 FluentValidation
我们可以使用 Nuget 下载最新的 FluentValidation 库
PM> Install-Package FluentValidation.AspNetCore
第二步: 添加 FluentValidation 服务
我们需要在 Startup.cs 文件中添加 FluentValidation 服务
- public void ConfigureServices(IServiceCollection services)
- {
- // mvc + validating
- services.AddMvc()
- .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
- .AddFluentValidation();
- }
添加校验器
FluentValidation 提供了多种内置的校验器. 在下面的例子中, 我们可以看到其中的 2 种
NotNull 校验器
NotEmpty 校验器
第一步: 添加一个需要验证的数据模型
下面我们添加一个 User 类.
- public class User
- {
- public string Gender { get; set; }
- public string FirstName { get; set; }
- public string LastName { get; set; }
- public string SIN { get; set; }
- }
第二步: 添加校验器类
使用 FluentValidation 创建校验器类, 校验器类都需要继承自一个抽象类 AbstractValidator
- public class UserValidator : AbstractValidator<User>
- {
- public UserValidator()
- {
- // 在这里添加规则
- }
- }
第三步: 添加验证规则
在这个例子中, 我们需要验证 FirstName, LastName, SIN 不能为 null, 不能为空. 我们也需要验证工卡 SIN(Social Insurance Number) 编号是合法的
- public static class Utilities
- {
- public static bool IsValidSIN(int sin)
- {
- if (sin <0 || sin> 999999998) return false;
- int checksum = 0;
- for (int i = 4; i != 0; i--)
- {
- checksum += sin % 10;
- sin /= 10;
- int addend = 2 * (sin % 10);
- if (addend>= 10) addend -= 9;
- checksum += addend;
- sin /= 10;
- }
- return (checksum + sin) % 10 == 0;
- }
- }
下面我们在 UserValidator 类的构造函数中, 添加验证规则
- public class UserValidator : AbstractValidator<User>
- {
- public UserValidator()
- {
- RuleFor(x => x.FirstName)
- .NotEmpty()
- .WithMessage("FirstName is mandatory.");
- RuleFor(x => x.LastName)
- .NotEmpty()
- .WithMessage("LastName is mandatory.");
- RuleFor(x => x.SIN)
- .NotEmpty()
- .WithMessage("SIN is mandatory.")
- .Must((o, list, context) =>
- {
- if (null != o.SIN)
- {
- context.MessageFormatter.AppendArgument("SIN", o.SIN);
- return Utilities.IsValidSIN(int.Parse(o.SIN));
- }
- return true;
- })
- .WithMessage("SIN ({SIN}) is not valid.");
- }
- }
第四步: 注入验证服务
- public void ConfigureServices(IServiceCollection services)
- {
- // 添加验证器
- services.AddSingleton<IValidator<User>, UserValidator>();
- // mvc + validating
- services
- .AddMvc()
- .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
- .AddFluentValidation();
- }
第五步: 在 Startup.cs 中管理你的验证错误
ASP.NET Core 2.1 及以上版本中, 你可以覆盖 ModelState 管理的默认行为 (ApiBehaviorOptions)
- public void ConfigureServices(IServiceCollection services)
- {
- // Validators
- services.AddSingleton<IValidator<User>, UserValidator>();
- // mvc + validating
- services
- .AddMvc()
- .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
- .AddFluentValidation();
- // override modelstate
- services.Configure<ApiBehaviorOptions>(options =>
- {
- options.InvalidModelStateResponseFactory = (context) =>
- {
- var errors = context.ModelState
- .Values
- .SelectMany(x => x.Errors
- .Select(p => p.ErrorMessage))
- .ToList();
- var result = new
- {
- Code = "00009",
- Message = "Validation errors",
- Errors = errors
- };
- return new BadRequestObjectResult(result);
- };
- });
- }
当数据模型验证失败时, 程序会执行这段代码.
在这个例子, 我设置了如何向客户端显示错误. 这里返回结果中, 我只是包含了一个错误代码, 错误消息以及错误对象列表.
下面让我们看一下最终效果.
使用验证器
这里验证器使用起来非常容易.
你只需要创建一个 action, 并将需要验证的数据模型放到 action 的参数中.
由于验证服务已在配置中添加, 因此当请求这个 action 时, FluentValidation 将自动验证你的数据模型!
第一步: 创建一个使用待验证数据模型的 action
- [Route("api/[controller]")]
- [ApiController]
- public class DemoValidationController : ControllerBase
- {
- [HttpPost]
- public IActionResult Post(User user)
- {
- return NoContent();
- }
- }
第二步: 使用 POSTMAN 测试你的 action
总结
在本篇博客中, 我讲解了如何使用 FluentValidation 进行数据模型验证.
本篇源代码
来源: https://www.cnblogs.com/lwqlun/p/10311945.html