.Net Core3.0 WEB API中使用FluentValidation驗證(批量注入)
為什么要使用FluentValidation
1.在日常的開發(fā)中,需要驗證參數(shù)的合理性,不緊前端需要驗證傳毒的參數(shù),后端也需要驗證參數(shù)
2.在領(lǐng)域模型中也應(yīng)該驗證,做好防御性的編程是一種好的習(xí)慣(其實以前重來不寫的,被大佬教育了一番)
3.FluentValidation 是.NET 開發(fā)的驗證框架,開源,主要是簡單好用,內(nèi)置了一些常用的驗證器,可以直接使用,擴展也很方便
使用FluentValidation
1.引入FluentValidation.AspNetCore NuGet包
2.建立需要驗證的類
/// <summary>
/// 創(chuàng)建客戶
/// </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<CreateCustomerDto>
{
  public CreateCustomerDtoValidator()
  {
    RuleFor(x => x.CustomerName)
       .NotEmpty()
       .WithMessage("客戶姓名不能為空");
    RuleFor(x => x.CustomerPhone)
       .NotEmpty()
       .WithMessage("客戶電話不能為空");
  }
}
3.統(tǒng)一返回驗證的信息,ResponseResult為全局統(tǒng)一參數(shù)返回的類
  /// <summary>
  /// 添加AddFluentValidationErrorMessage
  /// </summary>
  /// <returns></returns>
  public DependencyInjectionService AddFluentValidationErrorMessage()
  {
    _services.Configure<ApiBehaviorOptions>(options =>
    {
      options.InvalidModelStateResponseFactory = (context) =>
      {
        var errors = context.ModelState
          .Values
          .SelectMany(x => x.Errors
                .Select(p => p.ErrorMessage))
          .ToList();
        var result = new ResponseResult<List<string>>
        {
          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<IValidator>();比較麻煩每次新增都需要添加一次注入
所以我們使用批量的注入,來減少麻煩,通過反射獲取所有的驗證的類批量注入
  /// <summary>
  /// 添加MVC
  /// </summary>
  /// <returns></returns>
  public DependencyInjectionService AddMvc()
  {
    _services.AddControllers(options => 
    { 
      options.Filters.Add(typeof(LogHelper));
    }).AddJsonOptions(options =>
    {
      //忽略循環(huán)引用
      //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<Type> 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>
  /// 創(chuàng)建客戶
  /// </summary>
  /// <param name="input"></param>
  /// <returns></returns>
  [HttpPost]
  public async Task<ResponseResult<string>> CreateCustomer([FromBody] CreateCustomerDto input)
  {
    var createCustomerCommand = new CreateCustomerCommand(input.CustomerName,input.CustomerAge,input.CustomerPhone,input.CustomerAddress);
    await _commandService.SendCommandAsync(createCustomerCommand);
    var result = new ResponseResult<string>
    {
      IsSucceed = true,
      Result = "創(chuàng)建客戶成功!"
    };
    return result;
  }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持我們。
欄 目:ASP.NET
本文標(biāo)題:.Net Core3.0 WEB API中使用FluentValidation驗證(批量注入)
本文地址:http://www.jygsgssxh.com/a1/ASP_NET/10825.html
您可能感興趣的文章
- 01-11如何給asp.net core寫個簡單的健康檢查
 - 01-11淺析.Net Core中Json配置的自動更新
 - 01-11.net core高吞吐遠程方法如何調(diào)用組件XRPC詳解
 - 01-11.NET Core 遷移躺坑記續(xù)集之Win下莫名其妙的超時
 - 01-11.NET開發(fā)人員關(guān)于ML.NET的入門學(xué)習(xí)
 - 01-11docker部署Asp.net core應(yīng)用的完整步驟
 - 01-11.net core webapi jwt 更為清爽的認(rèn)證詳解
 - 01-11ASP.NET Core靜態(tài)文件的使用方法
 - 01-11.NET Core 3.0之創(chuàng)建基于Consul的Configuration擴展組件
 - 01-11.net core EF Core調(diào)用存儲過程的方式
 


閱讀排行
本欄相關(guān)
- 01-11vscode extension插件開發(fā)詳解
 - 01-11VsCode插件開發(fā)之插件初步通信的方法
 - 01-11如何給asp.net core寫個簡單的健康檢查
 - 01-11.net core高吞吐遠程方法如何調(diào)用組件
 - 01-11淺析.Net Core中Json配置的自動更新
 - 01-11.NET開發(fā)人員關(guān)于ML.NET的入門學(xué)習(xí)
 - 01-11.NET Core 遷移躺坑記續(xù)集之Win下莫名其
 - 01-11.net core webapi jwt 更為清爽的認(rèn)證詳解
 - 01-11docker部署Asp.net core應(yīng)用的完整步驟
 - 01-11ASP.NET Core靜態(tài)文件的使用方法
 
隨機閱讀
- 08-05DEDE織夢data目錄下的sessions文件夾有什
 - 04-02jquery與jsp,用jquery
 - 01-10使用C語言求解撲克牌的順子及n個骰子
 - 01-11Mac OSX 打開原生自帶讀寫NTFS功能(圖文
 - 08-05dedecms(織夢)副欄目數(shù)量限制代碼修改
 - 01-11ajax實現(xiàn)頁面的局部加載
 - 08-05織夢dedecms什么時候用欄目交叉功能?
 - 01-10delphi制作wav文件的方法
 - 01-10SublimeText編譯C開發(fā)環(huán)境設(shè)置
 - 01-10C#中split用法實例總結(jié)
 


