如何使用FluentValidation.AspNetCore和FluentValidation.MVC6?

How to use FluentValidation.AspNetCore and FluentValidation.MVC6?

如何使用 FluentValidation.AspNetCore 和 FluentValidation.MVC6 验证 AspNetCore 中的实体,谁能举个例子?

这对我有用:

project.json 添加:

"FluentValidation.AspNetCore": "6.4.0-beta3"

startup.cs

services
.AddMvc()
.AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<Startup>());

验证:

public class Foo
{
     public string Bar {get; set;}
}

public class FooValidator : AbstractValidator<Foo> 
{
    public FooValidator()
    { 
        RuleFor(x => x.Bar).NotEmpty().WithMessage("Error Message");
    }
}

首先你需要添加nuget Install-Package FluentValidation.AspNetCore

您可以有一个操作过滤器来处理验证:

public class ValidatorActionFilter : IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (!filterContext.ModelState.IsValid)
        {
            filterContext.Result = new BadRequestObjectResult(filterContext.ModelState);
        }
    }

    public void OnActionExecuted(ActionExecutedContext filterContext)
    {

    }
}

Startup.ConfigureServices 看起来像这样添加自动验证并添加 FluentValidation:

services.AddMvc(opt =>
        {
            opt.Filters.Add(typeof(ValidatorActionFilter));
        }).AddFluentValidation(fvc => 
   fvc.RegisterValidatorsFromAssemblyContaining<Startup>())

如果您需要阅读另一个程序集,请将其命名为 而不是 startUp

现在您可以添加验证以确保:

public class CreateCustomer
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
}

public class CreateCustomerValidator : AbstractValidator<CreateCustomer>
{
    public CreateCustomerValidator()
    {
        RuleFor(x => x.FirstName).NotNull().WithMessage(Resource.Validaton.FirstNameRequired);
        RuleFor(x => x.LastName).NotNull().WithMessage(Resource.Validaton.LastNameRequired);
        RuleFor(x => x.Email).Matches(@"\A(?:[a-z0-9!#$%&'*=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z").WithMessage(Resource.Validaton.EmailFormat);
    }
}