.NetCore3.0中怎么使用FluentValidation驗證-創(chuàng)新互聯(lián)

.Net Core3.0中怎么使用FluentValidation驗證?相信很多沒有經(jīng)驗的人對此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。

成都創(chuàng)新互聯(lián)自2013年起,先為閩清等服務(wù)建站,閩清等地企業(yè),進行企業(yè)商務(wù)咨詢服務(wù)。為閩清企業(yè)網(wǎng)站制作PC+手機+微官網(wǎng)三網(wǎng)同步一站式服務(wù)解決您的所有建站問題。

為什么要使用FluentValidation


1.在日常的開發(fā)中,需要驗證參數(shù)的合理性,不緊前端需要驗證傳毒的參數(shù),后端也需要驗證參數(shù)
2.在領(lǐng)域模型中也應(yīng)該驗證,做好防御性的編程是一種好的習慣(其實以前重來不寫的,被大佬教育了一番)
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)容,你們掌握.Net Core3.0中怎么使用FluentValidation驗證的方法了嗎?如果還想學到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!

網(wǎng)頁名稱:.NetCore3.0中怎么使用FluentValidation驗證-創(chuàng)新互聯(lián)
分享網(wǎng)址:http://www.muchs.cn/article44/hgche.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供標簽優(yōu)化、搜索引擎優(yōu)化域名注冊、自適應(yīng)網(wǎng)站移動網(wǎng)站建設(shè)、定制開發(fā)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

外貿(mào)網(wǎng)站制作