栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > asp

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

asp 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

  /// 
  /// 添加MVC
  /// 
  /// 
  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;
  }

  /// 
  /// 获取所有的FluentValidation Validator的类
  /// 
  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.使用起来就十分简单了

  /// 
  /// 创建客户
  /// 
  /// 
  /// 
  [HttpPost]
  public async Task> 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;
  }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/55027.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号