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

后端 未结 1 1325
迷失自我
迷失自我 2020-12-11 08:58

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 bu

相关标签:
1条回答
  • 2020-12-11 09:08

    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; }
    }
    
    0 讨论(0)
提交回复
热议问题