【问题标题】:Validating enums with FluentValidation使用 FluentValidation 验证枚举
【发布时间】:2017-01-06 13:07:14
【问题描述】:

我在 Web API 项目中使用 FluentValidation.WebApi 6.2.1.0。有没有办法使用 FluentValidation 验证枚举并返回自定义消息?

我的控制器动作如下,

public IHttpActionResult Get([FromUri]CheckUpdateVM info)
{
    ...
}

我的模特,

[Validator(typeof(CheckUpdateVMValidator))]
public class CheckUpdateVM
{
    public DeviceTypes Device { get; set; }
}

我正在寻找这样的东西,

public class CheckUpdateVMValidator : AbstractValidator<CheckUpdateVM>
{
    public CheckUpdateVMValidator()
    {
        RuleFor(x => x.Device).Must(x => Enum.IsDefined(typeof(DeviceTypes), x)).WithMessage("xxx");
    }
}

使用上面的代码,模型绑定器验证“设备”参数的值并以错误响应。但我无法自定义错误消息。 (如果我将“设备”属性类型设置为字符串,这可以正常工作。)

【问题讨论】:

    标签: asp.net asp.net-web-api enums fluentvalidation


    【解决方案1】:

    在这种情况下,创建自定义验证器可能是更好的方法。

    public class DeviceEnumValidator<T> : PropertyValidator {
    
    public DeviceEnumValidator() 
        : base("Invalid Enum value!") { }
    
    protected override bool IsValid(PropertyValidatorContext context) { 
    
        DeviceTypes enumVal= (DeviceTypes) Enum.Parse(typeof(DeviceTypes), context.PropertyValue);
    
        if (!Enum.IsDefined(typeof(DeviceTypes), enumVal) 
          return false;
    
        return true;
     }
    }
    

    要使用 DeviceEnumValidator,您可以在定义验证规则时调用 SetValidator。

    public CheckUpdateVMValidator()
    {
        RuleFor(x => x.Device).SetValidator(new DeviceEnumValidator<DeviceTypes>());
    }
    

    【讨论】:

      猜你喜欢
      • 2017-12-14
      • 2019-04-30
      • 1970-01-01
      • 2010-09-06
      • 2012-07-01
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多