Custom Model Validator for Integer value in ASP.NET Core Web API

情到浓时终转凉″ 提交于 2019-12-02 04:01:56

问题


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

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.


回答1:


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.

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: Could not convert string to integer: abc. Path 'Level', ...

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


来源:https://stackoverflow.com/questions/49300906/model-validation-is-not-working-in-asp-net-core-2-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!