• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

.Net Core3.0 WEB API中使用FluentValidation验证(批量注入)

asp 搞代码 4年前 (2022-01-03) 33次浏览 已收录 0个评论

这篇文章主要介绍了.Net Core3.0 WEB API中使用FluentValidation验证(批量注入),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

为什么要使用FluentValidation

1.在日常的开发中,需要验证参数的合理性,不紧前端需要验证传毒的参数,后端也需要验证参数
2.在领域模型中也应该验证,做好防御性的编程是一种好的习惯(其实以前重来不写的,被大佬教育了一番)
3.FluentValidation 是.NET 开发的验证框架,开源,主要是简单好用,内置了一些常用的验证器,可以直接使用,扩展也很方便

使用FluentValidation

1.引入FluentValidation.AspNetCore NuGet包
2.建立需要验证的类

 /// <summary> /// 创建客户 /// </summary> public class CreateCustomerDto { /// <summary> /// 客户姓名 /// </summary> public string CustomerName { get; set; } /// <summary> /// 客户年龄 /// </summary> public string CustomerAge { get; set; } /// <summary> /// 客户电话 /// </summary> public string CustomerPhone { get; set; } /// <summary> /// 客户地址 /// </summary> public Address CustomerAddress { get; set; } } /// <summary> /// 验证 /// </summary> public class CreateCustomerDtoValidator : AbstractValidator { public CreateCustomerDtoValidator() { RuleFor(x => x.CustomerName) .NotEmpty() .WithMessage("客户姓名不能为空"); RuleFor(x => x.CustomerPhone) .NotEmpty() .WithMessage("客户电话不能为空"); } } 

3.统一返回验证的信息,ResponseResult

来源gao!%daima.com搞$代*!码网

为全局统一参数返回的类

 /// <summary> /// 添加AddFluentValidationErrorMessage /// </summary> ///  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<List> { 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();比较麻烦每次新增都需要添加一次注入
所以我们使用批量的注入,来减少麻烦,通过反射获取所有的验证的类批量注入

 /// <summary> /// 添加MVC /// </summary> ///  public DependencyInjectionService AddMvc() { _services.AddControllers(options => { options.Filters.Add(typeof(LogHelper)); }).AddJsonOptions(options => { //忽略循环引用 //options.JsonSerializerOptions.IgnoreReadOnlyProperties = true; }).AddFluentValidation(options => { options.RunDefaultMvcValidationAfterFluentValidationExecutes = false; var validatorList = GetFluentValidationValidator("ConferenceWebApi"); foreach (var item in validatorList) { options.RegisterValidatorsFromAssemblyContaining(item); } }); return _dependencyInjectionConfiguration; } /// <summary> /// 获取所有的FluentValidation Validator的类 /// </summary> public IEnumerable GetFluentValidationValidator(string assemblyName) { if (assemblyName == null) throw new ArgumentNullException(nameof(assemblyName)); if (string.IsNullOrEmpty(assemblyName)) throw new ArgumentNullException(nameof(assemblyName)); var implementAssembly = RuntimeHelper.GetAssembly(assemblyName); if (implementAssembly == null) { throw new DllNotFoundException($"the dll ConferenceWebApi not be found"); } var validatorList = implementAssembly.GetTypes().Where(e => e.Name.EndsWith("Validator")); return validatorList; } 

5.使用起来就十分简单了

 /// <summary> /// 创建客户 /// </summary> ///  ///  [HttpPost] public async Task<ResponseResult> CreateCustomer([FromBody] CreateCustomerDto input) { var createCustomerCommand = new CreateCustomerCommand(input.CustomerName,input.CustomerAge,input.CustomerPhone,input.CustomerAddress); await _commandService.SendCommandAsync(createCustomerCommand); var result = new ResponseResult { IsSucceed = true, Result = "创建客户成功!" }; return result; } 

以上就是.Net Core3.0 WEB API中使用FluentValidation验证(批量注入)的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:.Net Core3.0 WEB API中使用FluentValidation验证(批量注入)

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址