How are data annotation attributes to be used with method parameters? I'm expecting to do something like this, but an exception isn't thrown.
private string TestValidate([StringLength(5)] string name = "Default: throw exception")
{
ValidationContext context = new ValidationContext(name);
Validator.ValidateObject(name, context);
return name;
}
Alternatively, I know this will work. However, this doesn't use the convenience of the attribute convention.
private string TestValidate(string name = "Default: throw exception")
{
ValidationContext context = new ValidationContext(name);
Validator.ValidateValue(name, context, new[] { new StringLengthAttribute(5) });
return name;
}
If you are wanting to instrument your code, then you'd use a bit of reflection (see https://msdn.microsoft.com/en-us/library/system.reflection.parameterinfo.attributes(v=vs.110).aspx)
You can evaluate your reflection once on class initialization, but this is how the reflection code would work:
Many validation frameworks simply encapsulate all the reflection necessary to get at the validation attributes. NOTE: in this case I used the subclass of
ValidationAttribute
as opposed to the more specificStringLengthAttribute
. The call toGetCustomAttributes()
will return any attribute that extends the base class we asked for. That allows you to completely change the attributes you have on your method and add more constraints without changing the code at all. You'll have to make some changes if you evaluate more than one parameter or remove a parameter.You could make this a bit more generic as the code from the time you have a specific
MethodInfo
object would be generally the same. I'd probably make a couple changes in that case: