In netcore 3.1 api service I use attributes for properties from UoN.ExpressiveAnnotations (https://www.nuget.org/packages/UoN.ExpressiveAnnotations.NetCore/):
public class Data
{
[AssertThat("IsPhone(Phone)")]
[Required(AllowEmptyStrings = false)]
[JsonPropertyName("phone_number")]
public string PhoneNumber { get; set; }
}
For RequiredAttribute I created something like this and it works ok:
public sealed class RequiredAttribute: System.ComponentModel.DataAnnotations.RequiredAttribute
{
private string jsonPropertyName;
public RequiredAttribute()
{
this.ErrorMessage = PropertyErrorMsgs.PropertyRequired;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var attributes = validationContext.ObjectType
.GetProperty(validationContext.MemberName)
.GetCustomAttributes(typeof(JsonPropertyNameAttribute), true);
if (attributes != null)
this.jsonPropertyName = (attributes[0] as JsonPropertyNameAttribute).Name;
else
this.jsonPropertyName = validationContext.MemberName;
return base.IsValid(value, validationContext);
}
public override string FormatErrorMessage(string name)
{
return string.Format(this.ErrorMessageString, this.jsonPropertyName);
}
}
I want to override the error message for every AssertThatAttribute, in the same way: to use jsonPropertyName. But the problem that AssertThatAttribute was created as a sealed class so I can not inherit it. I also try playing with adapters but it did not work for me (maybe because of my mistakes when trying). PropertyErrorMsgs.PropertyRequired comes from ResourceFile (the value: '{0}' json field is required)
What is the best way to do in such conditions?