3

I have been developing a Web API with ASP.NET Core 2.0 framework. To validate the model, I have used data annotation attributes. There is also a Filter class which executes for validating the models in request pipeline. This filter class works fine but it throws an exception while data type is different.

Here is my Model Class with validator attribute

public class MyModelClass
{        
    [RegularExpression("([1-4]+)", ErrorMessage = "{0} must be a Integer Value")]
    [Range(1, 4, ErrorMessage = "{0} must between 1 and 4")]
    [Required(ErrorMessage = "{0} is required")]
    public int Level { get; set; }    

    [DataType(DataType.DateTime, ErrorMessage = "Not a Valid date")]
    [Required(ErrorMessage = "{0} is required")]
    public DateTime Started { get; set; }
}

Here is my validation attribute class below:

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

For the request with below JSON object in Postman, I find the proper error message and no exception happens

Request JSON Object in Postman:

{  
  "Level": 6,
  "Started": "2018-03-15T09:09:24.003Z",  
}

Response JSON Object in Postman:

{
"Errors": 
    {
    "Level": [
        "Level must between 1 and 4"
    ]
    }
}

But if I send a request with an invalid data type, then the validation message stated into the model attributes are not showing, instead, an exception message is showing.

Request with invalid JSON Object in Postman:

{  
  "Level": "Hello",
  "Started": "DD-MM-YYYY",  
}

Response JSON Object with exception message in Postman:

{    
    "Errors": {
        "Started": [
            "Could not convert string to DateTime: DD-MM-YYYY. Path 'Started', line 6, position 25."
        ],
        "Level": [
            "Could not convert string to integer: Hello. Path 'Level', line 5, position 24."
        ]
    }
}

From the error message, I found that the RegularExpression and DataType.DateTime validator is not working. I do not understand the problem. Can anyone please let me know why the above code is not working.

Please also give me proper suggestions how can I have the proper validation message which is stated in the data annotation.

mnu-nasir
  • 1,642
  • 5
  • 30
  • 62
  • 1
    Check my answer to your recent question - https://stackoverflow.com/questions/49301360/custom-model-validator-for-integer-value-in-asp-net-core-web-api/49305472#49305472. It addresses the both problems as they are linked. In short: model validation happens only if model is successfully deserialized. The error you see `Could not convert string to DateTime` comes from deserializer (JSON.Net). If model fails to deserialize, then no model validation will happen, there is just no model for validation. – CodeFuller Mar 15 '18 at 18:21
  • @CodeFuller, thanks for your great answer. It really helps me. Can you please let me know, either it is possible to handle the problem before the request handles by the JSON.Net library. Is there any way to perform some manual tasks in the application request cycle? – mnu-nasir Mar 17 '18 at 15:58

0 Answers0