Attribute on Interface members does not work

2019-01-07 22:06发布

In my application several models need Password properties (eg, Registration and ChangePassword models). The Password property has attribute like DataType and Required. Therefore to ensure of re-usability an consistency, I created :

interface IPasswordContainer{
    [Required(ErrorMessage = "Please specify your password")]
    [DataType(DataType.Password)]
    string Password { get; set; }
} 

And

class RegistrationModel : IPasswordContainer {
    public string Password { get; set; }
}

Unfortunately, the attributes does not work.

Then I tried changing the interface to a class:

public class PasswordContainer {
    [Required(ErrorMessage = "Please specify your password")]
    [DataType(DataType.Password)]
    public virtual string Password { get; set; }
}

And

public class RegistrationModel : PasswordContainer {
    public override string Password { get; set; }
}

Now it is working. Why it is so?

Why the attributes are working when inherited from class but not working when inherited from interface?

1条回答
霸刀☆藐视天下
2楼-- · 2019-01-07 22:52

Attributes on interface properties doesn't get inherited to the class, you may make your interface an Abstract Class.

Found an answer from Microsoft:

The product team does not want to implement this feature, for two main reasons:

  • Consistency with DataAnnotations.Validator
  • Consistency with validation behavior in ASP.Net MVC
  • tricky scenario: a class implements two interfaces that have the same property, but with conflicting attributes on them. Which attribute would take precedence?
查看更多
登录 后发表回答