csharp FluentValidation作为服务.Net Core 2

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp FluentValidation作为服务.Net Core 2相关的知识,希望对你有一定的参考价值。

private IValidator<MyModel> _pv;
//ctor
public ModelController(IValidator<MyModel> pv)
{
    _pv = pv;
}

[HttpPost("add")]
public bool Post([FromBody] MyModel model)
{
    var x = _pv.Validate(model, ruleSet: "common").IsValid;
    return x;
}
RuleSet("common", () =>
{
    RuleFor(x => x.Id)
        .NotEmpty()
        .NotNull()
        .WithMessage("ID must not be empty, please add an ID property");
});
  
  
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public bool Active { get; set; }
services.AddMvc()
  .AddFluentValidation(fvc => 
    fvc.RegisterValidatorsFromAssemblyContaining<MyModelValidator>())
      .AddJsonOptions(o => o.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver());

services.AddTransient<IValidator<MyModel>, MyModelValidator>();

以上是关于csharp FluentValidation作为服务.Net Core 2的主要内容,如果未能解决你的问题,请参考以下文章

模型验证组件 FluentValidation

模型验证组件 FluentValidation

FluentValidation.NET 等效于 [Display(Name)]

FluentValidation:验证仅设置了一个属性

在 .NET Core 中使用 FluentValidation 和依赖注入

FluentValidation 谓词验证器不起作用