自定义模型验证器,用于ASP.NET Core Web API中的整数值

mnu*_*sir 4 model-validation data-annotations asp.net-core-2.0

我已经开发了一个自定义验证器Attribute类,用于检查模型类中的Integer值。但问题是此类无法正常工作。我已经调试了我的代码,但是在调试代码期间没有遇到断点。这是我的代码:

public class ValidateIntegerValueAttribute : ValidationAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value != null)
            {
                int output;

                var isInteger = int.TryParse(value.ToString(), out output);

                if (!isInteger)
                {
                    return new ValidationResult("Must be a Integer number");
                }
            }

            return ValidationResult.Success;
        }
    }
Run Code Online (Sandbox Code Playgroud)

我还有一个Filter类,用于在应用程序请求管道中全局进行模型验证。这是我的代码:

public class MyModelValidatorFilter: IActionFilter
{   
    public void OnActionExecuting(ActionExecutingContext context)
    {
        if (context.ModelState.IsValid)
            return;

        var errors = new Dictionary<string, string[]>();

        foreach (var err in actionContext.ModelState)
        {
            var itemErrors = new List<string>();

            foreach (var error in err.Value.Errors){
                itemErrors.Add(error.Exception.Message);
            }

            errors.Add(err.Key, itemErrors.ToArray());
        }

        actionContext.Result = new OkObjectResult(new MyResponse
        {
            Errors = errors
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

带有验证的模型类如下:

public class MyModelClass
Run Code Online (Sandbox Code Playgroud)

{

[ValidateIntegerValue(ErrorMessage = "{0} must be a Integer Value")]
[Required(ErrorMessage = "{0} is required")]
public int Level { get; set; }        
Run Code Online (Sandbox Code Playgroud)

}

谁能让我知道为什么整数整数验证类不起作用。

Cod*_*ler 6

从请求反序列化模型后,模型验证就起作用了。如果模型包含整数字段,Level并且您发送的值无法反序列化为整数(例如“ abc”),则模型甚至不会反序列化。结果,验证属性也不会被调用-仅没有用于验证的模型。

考虑到这一点,实现这样没有太大意义ValidateIntegerValueAttribute。在这种情况下,反序列化程序JSON.Net已经执行了这种验证。您可以通过检查控制器操作中的模型状态来验证这一点。ModelState.IsValid将设置为,false并且ModelState错误袋将包含以下错误:

Newtonsoft.Json.JsonReaderException:无法将字符串转换为整数:abc。路径“级别”,...

要添加的另一件事:为使Required验证属性正确工作,您应该使基础属性为可空。否则,该属性将0在模型反序列化器之后保留为其默认值()。模型验证无法区分缺失值和等于默认值的值。因此,为了Required使属性正确工作,请将属性设为可空:

public class MyModelClass
{
    [Required(ErrorMessage = "{0} is required")]
    public int? Level { get; set; }
}
Run Code Online (Sandbox Code Playgroud)