【发布时间】:2021-01-14 22:12:07
【问题描述】:
我正在尝试使用自定义验证器来验证智能枚举 (Ardalis.SmartEnum)
这是枚举的类:
public abstract class FeelingSystemType : SmartEnum<FeelingSystemType>
{
public static FeelingSystemType Positive = new PositiveType();
public static FeelingSystemType Negative = new NegativeType();
private FeelingSystemType(string name, int value) : base(name, value) { }
private class PositiveType : FeelingSystemType
{
internal PositiveType() : base(nameof(Positive), 1) { }
}
private class NegativeType : FeelingSystemType
{
internal NegativeType() : base(nameof(Negative), 2) { }
}
}
这是命令:
public class Command : IRequest<CommandResponsem>
{
public Command() { }
[JsonConverter(typeof(SmartEnumNameConverter<FeelingSystemType, int>))]
public FeelingSystemType Feeling { get; set; }
}
这是命令验证器:
public class CommandValidator : AbstractValidator<Command>
{
public CommandValidator()
{
RuleFor(r => r.Feeling).ValidateFeeling();
}
}
这是自定义验证规则:
public static IRuleBuilder<T, FeelingSystemType> ValidateFeeling<T>(this IRuleBuilder<T, FeelingSystemType> rule)
{
return rule
.NotEmpty()
.WithMessage("A Feeling must be entered")
.Must(feeling => typeof(FeelingSystemType).IsAssignableFrom(feeling?.GetType()))
.WithMessage("Please enter a valid Feeling");
}
当我发送请求时,验证器似乎忽略了 NotEmpty 在规则的 Must 部分之前,即使 Feeling 为空,它仍然继续验证 Must,但同时返回两条消息。我尝试在命令验证器中进行验证,并且得到相同的结果,除非我将 NotEmpty 和 Must 作为两个单独的规则执行。我非常有信心 Fluent 允许链接,所以我不确定这里出了什么问题?
【问题讨论】:
标签: c# fluentvalidation