.Net Core3.0 WEB API 中使用FluentValidation验证,实现批量注入
阅读目录
为什么要使用FluentValidation
使用FluentValidation
FluentValidation学习的资料
回到顶部
为什么要使用FluentValidation
1.在日常的开发中,需要验证参数的合理性,不紧前端需要验证传毒的参数,后端也需要验证参数
2.在领域模型中也应该验证,做好防御性的编程是一种好的习惯(其实以前重来不写的,被大佬教育了一番)
3.FluentValidation 是.NET 开发的验证框架,开源,主要是简单好用,内置了一些常用的验证器,可以直接使用,扩展也很方便
回到顶部
使用FluentValidation
1.引入FluentValidation.AspNetCore NuGet包
2.建立需要验证的类
复制代码
///
/// 创建客户
///
public class CreateCustomerDto
{
///
/// 客户姓名
///
public string CustomerName { get; set; }
///
/// 客户年龄
///
public string CustomerAge { get; set; }
///
/// 客户电话
///
public string CustomerPhone { get; set; }
///
/// 客户地址
///
public Address CustomerAddress { get; set; }
}
///
/// 验证
///
public class CreateCustomerDtoValidator : AbstractValidator
{
public CreateCustomerDtoValidator()
{
RuleFor(x => x.CustomerName)
.NotEmpty()
.WithMessage("客户姓名不能为空");
RuleFor(x => x.CustomerPhone)
.NotEmpty()
.WithMessage("客户电话不能为空");
}
}
复制代码
3.统一返回验证的信息,ResponseResult为全局统一参数返回的类
复制代码
///
/// 添加AddFluentValidationErrorMessage
///
///
public DependencyInjectionService AddFluentValidationErrorMessage()
{
_services.Configure(options =>
{
options.InvalidModelStateResponseFactory = (context) =>
{
var errors = context.ModelState
.Values
.SelectMany(x => x.Errors
.Select(p => p.ErrorMessage))
.ToList();
var result = new ResponseResult
- >
{
StatusCode = "00009",
Result = errors,
Message = string.Join(",", errors.Select(e => string.Format("{0}", e)).ToList()),
IsSucceed = false
};
return new BadRequestObjectResult(result);
};
});
return _dependencyInjectionConfiguration;
}
复制代码
4.注入验证的类
使用builder.RegisterType().As