Use of .Net Core data validation framework

In order to improve the response speed and interface usability, the data filled in by the user is generally verified on the client side, so that the user knows that the data is filled in incorrectly without sending the data to the server. But we can't completely rely on the client's verification, not only because malicious users can bypass the client's verification and send requests directly to the server, but also the server needs to do a thorough job for the client developers where the data verification is not in place. Therefore, the server side should also perform data verification.

The .Net Core framework itself also has built-in data verification, such as required verification [Require], etc., but the verification needs to be written on the class itself. The verification rules and model classes have a high coupling, which violates the principle of single responsibility. On the other hand, there are not enough built-in validation rules.

Based on the above reasons, use the FluentValidation data verification framework to verify data. Next, use the framework to verify data in the .Net Core WebAPI project.

1. Create a project and reference related packages

fluentvalidation.aspnetcore

2. Add the code for registering related services in Program.cs

builder.Services.AddFluentValidation(fv =>
{
    Assembly assembly = Assembly.GetExecutingAssembly();
    fv.RegisterValidatorsFromAssembly(assembly);
});

The RegisterValidatorsFromAssembly method is used to register all data validation classes that implement the IValidator interface in the specified assembly to the dependency injection container. Because all the data validation classes of this project are written in one project, use RegisterValidatorsFromAssembly to get the assembly of the entry project.

If there are multiple assemblies, you need to call RegisterValidatorsFromAssemblies to execute these assemblies for registration.

3. Write the model class

namespace WebApplication1
{
    public record LoginRequest(string Email, string Password, string Password2);
}

4. Write a data validation class

using FluentValidation;

namespace WebApplication1
{
    public class LoginRequestVaildator : AbstractValidator<LoginRequest>
    {
        public LoginRequestVaildator()
        {
            RuleFor(x => x.Email).NotNull().EmailAddress()
                .Must(v => v.EndsWith("@qq.com") || v.EndsWith("@163.com"))
                .WithMessage("只支持QQ和163邮箱");

            RuleFor(x => x.Password).NotNull().Length(3, 10)
                .WithMessage("密码必须介于3到10位之间")
                .Equal(x => x.Password2).WithMessage("两次密码必须一致");
        }
    }
}

The data validation class is generally integrated from AbstractValidator. AbstractValidator is a generic class. It is necessary to specify which class the data validation class verifies through generic parameters; the validation rules need to be written in the construction method of the validation class;

5. Write an action method

        [HttpPost]
        public void dataVaild(LoginRequest login) {
            Console.WriteLine(login.Password);
        }

Use LoginRequest as a parameter, and then send data to the path corresponding to this operation method on the client side.

 

After using FluentValidation, you can write the data verification rules into a separate book verification class, so that the model class and data verification class perform their own duties, in line with the "single responsibility principle", and write custom verification in FluentValidation The code is also simpler.

Guess you like

Origin blog.csdn.net/liangmengbk/article/details/130813503