In an web application made with .NET 8 and C#, my attribute validator that has heritage with ValidationAttribute is not working, when I put a breakpoint, the class is never called.
I will show you an example:
The next code is the attribute validator for a key attribute:
namespace SergioApp.Library.ModelAttributeValidator
{
public class KeyAttribute : ValidationAttribute
{
private string _PropertyName;
public KeyAttribute(string PropertyName)
{
try
{
if (PropertyName == null) { throw new Exception("The property name is empty"); }
if (PropertyName.Length < 0) { throw new Exception($"The length of property name must be equal or greater than 0"); }
if (PropertyName.Length > int.MaxValue) { throw new Exception($"The length of property name must be equal or less than int.MaxValue"); }
_PropertyName = PropertyName;
}
catch (Exception) { throw; }
}
public override bool IsValid(object? objPrimaryKey)
{
try
{
if (objPrimaryKey == null) { throw new Exception($"{_PropertyName} not found"); }
if (Convert.ToInt32(objPrimaryKey) < 0) { throw new Exception($"{_PropertyName} must be equal or better than 0"); }
if (Convert.ToInt32(objPrimaryKey) > int.MaxValue) { throw new Exception($"{_PropertyName} must be equal or less than int.MaxValue"); }
return true;
}
catch (Exception) { throw; }
}
}
}
And here is supposed to get executed that class using the decorator Key(“UserId”):
[Library.ModelAttributeValidator.Key("UserId")]
public int UserId { get; set; }
Did anyone solved it? Thanks.
By the way, is it good coded the attributes for keys in a SQL table?