如何忽略空对象的FluentValidation规则。 我的验证器类为
public class RequestModel
{
public int? RecordCount { get; set; } = 100;
}
public class ModelValidator : AbstractValidator<RequestModel>
{
public ModelValidator()
{
When(x => x != null, () =>
{
RuleFor(item => item.RecordCount)
.Cascade(CascadeMode.StopOnFirstFailure)
.Must(x => x == null || (x.Value > 0 && x.Value <= 1000))
.WithMessage($"Invalid Limit. Limit must be between 1 and {1000}. (inclusive) ");
});
}
}
在这里,我只想验证记录计数是否通过。 但是,当我将null对象传递给api主体时,它给出了
错误错误请求。该请求包含一些无效的参数,或其中的参数不足。
答案 0 :(得分:1)
我不太确定“ api主体”,但是如果要传递空对象,则需要在Validate
类中重写ModelValidator
方法。这样,您可以根据业务逻辑优雅地通过或失败此类对象。
这里是一个例子:
using FluentValidation;
using FluentValidation.Results;
using System;
using System.Linq;
namespace ConsoleApp13
{
public class RequestModel
{
public int? RecordCount { get; set; } = 100;
}
public class ModelValidator : AbstractValidator<RequestModel>
{
public ModelValidator()
{
When(x => x != null, () =>
{
RuleFor(item => item.RecordCount)
.Cascade(CascadeMode.StopOnFirstFailure)
.Must(x => x == null || (x.Value > 0 && x.Value <= 1000))
.WithMessage($"Invalid Limit. Limit must be between 1 and {1000}. (inclusive) ");
});
}
public override ValidationResult Validate(ValidationContext<RequestModel> context)
{
if (context.InstanceToValidate != null)
{
return base.Validate(context);
}
//if you want to pass
return new ValidationResult();
//if you want to fail
//return new ValidationResult(new[] { new ValidationFailure("Property", "Your Message") });
}
}
class Program
{
static void Main(string[] args)
{
RequestModel rm1 = new RequestModel { RecordCount = null };
RequestModel rm2 = new RequestModel { RecordCount = 100 };
RequestModel rm3 = new RequestModel { RecordCount = -100 };
RequestModel rm4 = null;
ModelValidator v = new ModelValidator();
ValidationResult result1 = v.Validate(rm1);
ValidationResult result2 = v.Validate(rm2);
ValidationResult result3 = v.Validate(rm3);
ValidationResult result4 = v.Validate(rm4);
Console.WriteLine($"IsValid (rm1): {result1.IsValid}\t| {GetError(result1)}");
Console.WriteLine($"IsValid (rm2): {result2.IsValid}\t| {GetError(result2)}");
Console.WriteLine($"IsValid (rm3): {result3.IsValid}\t| {GetError(result3)}");
Console.WriteLine($"IsValid (rm4): {result4.IsValid}\t| {GetError(result4)}");
Console.ReadKey();
}
static string GetError(ValidationResult result)
{
return result.IsValid == false ? string.Join(',', result.Errors.Select(k => k.ErrorMessage).ToArray()) : string.Empty;
}
}
}
结果是这样的:
我希望对您有帮助