自定义模型验证器,用于ASP.NET Core Web API中的整数值 [英] Custom Model Validator for Integer value in ASP.NET Core Web API

查看:357
本文介绍了自定义模型验证器,用于ASP.NET Core Web API中的整数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have developed a custom validator Attribute class for checking Integer values in my model classes. But the problem is this class is not working. I have debugged my code but the breakpoint is not hit during debugging the code. Here is my code:

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;
        }
    }

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

I have also an Filter class for model validation globally in application request pipeline. Here is my code:

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
        });
    }
}

具有验证的模型类如下:

The model class with validation is below:

public class MyModelClass

{

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

}

任何人都可以让我知道为什么整数整数验证类不起作用.

Can anyone please let me know why the attribute integer validation class is not working.

推荐答案

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

Model validation comes into play after the model is deserialized from the request. If the model contains integer field Level and you send value that could not be deserialized as integer (e.g. "abc"), then model will not be even deserialized. As result, validation attribute will also not be called - there is just no model for validation.

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

Taking this, there is no much sense in implementing such ValidateIntegerValueAttribute. Such validation is already performed by deserializer, JSON.Net in this case. You could verify this by checking model state in controller action. ModelState.IsValid will be set to false and ModelState errors bag will contain following error:

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

Newtonsoft.Json.JsonReaderException: Could not convert string to integer: abc. Path 'Level', ...

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

One more thing to add: for correct work of Required validation attribute, you should make the underlying property nullable. Without this, the property will be left at its default value (0) after model deserializer. Model validation has no ability to distinguish between missed value and value equal to default one. So for correct work of Required attribute make the property nullable:

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

这篇关于自定义模型验证器,用于ASP.NET Core Web API中的整数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆