. net core3.0 use fluent validation validation in Web API (batch injection)

Time:2020-4-5

Why use fluent validation

1. In daily development, it is necessary to verify the rationality of parameters, not only the front-end needs to verify the parameters of virus transmission, but also the back-end needs to verify the parameters
2. It should also be verified in the domain model that it’s a good habit to do defensive programming well (in fact, what I didn’t write before was taught by the big guy)
3. Fluent validation is a validation framework developed by. Net. It is open-source, mainly simple and easy to use. Some commonly used validators are built in, which can be used directly and expanded easily

Using fluent validation

1. Introduce the fluentvalidation.aspnetcore nuget package
2. Establish the class to be verified

/// <summary>
///Create customer
/// </summary>
public class CreateCustomerDto
{
  /// <summary>
  ///Customer name
  /// </summary>
  public string CustomerName { get; set; }
  /// <summary>
  ///Customer age
  /// </summary>
  public string CustomerAge { get; set; }
  /// <summary>
  ///Customer phone
  /// </summary>
  public string CustomerPhone { get; set; }
  /// <summary>
  ///Customer address
  /// </summary>
  public Address CustomerAddress { get; set; }
}

/// <summary>
// / verification
/// </summary>
public class CreateCustomerDtoValidator : AbstractValidator<CreateCustomerDto>
{
  public CreateCustomerDtoValidator()
  {
    RuleFor(x => x.CustomerName)
       .NotEmpty()
       . withmessage ("customer name cannot be empty");
    RuleFor(x => x.CustomerPhone)
       .NotEmpty()
       . withmessage ("customer phone number cannot be empty");

  }
}

3. Return the validation information uniformly. Responseresult is the class returned by the global unified parameter

/// <summary>
  ///Add addfluent validationerrormessage
  /// </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. Class for injection verification

Use builder. Registertype(). As < ivalidator > (); it is troublesome to add an injection every time
So we use batch injection to reduce the trouble and obtain all the verified class batch injection through reflection

/// <summary>
  ///Add MVC
  /// </summary>
  /// <returns></returns>
  public DependencyInjectionService AddMvc()
  {
    _services.AddControllers(options => 
    { 
      options.Filters.Add(typeof(LogHelper));
    }).AddJsonOptions(options =>
    {
      //Ignore circular references
      //options.JsonSerializerOptions.IgnoreReadOnlyProperties = true;
    }).AddFluentValidation(options =>
    {
      options.RunDefaultMvcValidationAfterFluentValidationExecutes = false;
      var validatorList = GetFluentValidationValidator("ConferenceWebApi");
      foreach (var item in validatorList)
      {
        options.RegisterValidatorsFromAssemblyContaining(item);
      }
    });
    return _dependencyInjectionConfiguration;
  }

  /// <summary>
  ///Get the class of all fluentvalidation validators
  /// </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. It’s very easy to use

/// <summary>
  ///Create customer
  /// </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 = "customer created successfully! "
    };
    return result;
  }

The above is the whole content of this article. I hope it will help you in your study, and I hope you can support developepaer more.

Recommended Today

Review of SQL Sever basic command

catalogue preface Installation of virtual machine Commands and operations Basic command syntax Case sensitive SQL keyword and function name Column and Index Names alias Too long to see? Space Database connection Connection of SSMS Connection of command line Database operation establish delete constraint integrity constraint Common constraints NOT NULL UNIQUE PRIMARY KEY FOREIGN KEY DEFAULT […]