I'm having an issue where I am trying to determine which ValidationAttribute returned a particular ModelError. I have an endpoint in my web api that takes a model such as;
public class MyClass
{
[Required]
[Range(0, 3)]
public int? Number { get; set; }
[Required]
[Range(0, 3)]
public int? NumberTwo { get; set; }
}
and a filter to check that the ModelState is valid;
public class ValidateModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (!actionContext.ModelState.IsValid)
{
IEnumerable<ModelError> errors = actionContext.ModelState.Values.SelectMany(s => s.Errors);
// ...
}
}
}
I see that the ModelError has two properties; ErrorMessage which is of type string, and Exception which is of type Exception. I would like a strongly typed way to determine which ValidationAttribute [Required] or [Range(0, 3)] returned the error response without doing string manipulation. Is there a way to return a custom property using these attributes that I am unfamiliar with?
If the client were to post a model such as
{
"NumberTwo":10
}
The end goal would be to produce a response from the API such as the following;
{
"supportCode" : "1234567890",
"errors" : [{
"code" : "Missing",
"message" : "The Number field is required."
}, {
"code" : "Invalid",
"message" : "The field NumberTwo must be between 0 and 3."
}]
}