Skip to content

Validation

ZhangYang edited this page Jul 27, 2019 · 1 revision

Fluent Validation

Fluent Validation is used in RestAirline for request model validation.

Config Fluent Validation in Startup class

services.AddMvc(options =>
                {
                  //...
                })
                .AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<AddPassengerCommandValidator>());;

AddFromAssemblyContaining method to automatically register all validators within a particular assembly. This will automatically find any public, non-abstract types that inherit from AbstractValidator and register them with the container.

Create AddPassengerCommandValidator

    public class AddPassengerCommandValidator : AbstractValidator<AddPassengerCommand>
    {
        public AddPassengerCommandValidator()
        {
            RuleFor(x => x.Age)
                .InclusiveBetween(1, 100)
                .WithMessage("Age must between 15 to 100")
                .When(x => x.PassengerType != PassengerType.Infant);

            RuleFor(x => x.Age)
                .LessThan(1)
                .WithMessage("Infant must less 1")
                .When(x => x.PassengerType == PassengerType.Infant);

            RuleFor(x => x.Name)
                .Length(2, 50).WithMessage("Name can not be empty");

            RuleFor(x => x.Email).EmailAddress();
        }
    }

Create ModelState validation Filter

Instead of using below code in every action

public async Task<IActionResult> AddPerson(PersonAddModel model)
{
    if(ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    // ......
}

We can add a filter to intercept all bad request during action execution:

    public class ModelValidationFilter : IActionFilter
    {
        private readonly ILogger<ModelValidationFilter> _logger;

        public ModelValidationFilter(ILogger<ModelValidationFilter> logger)
        {
            _logger = logger;
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                context.Result = new BadRequestObjectResult(context.ModelState);

                _logger.LogInformation(context.Result .SerializeToCamelCase());
            }
        }

        public void OnActionExecuted(ActionExecutedContext context)
        {
            // Do not need implementation in this class.
        }
    }

Register filter in Startup class

 services.AddMvc(options =>
                {
                    options.Filters.Add<ModelValidationFilter>();
                    //...
                })
Clone this wiki locally