如何为每个程序集仅定义一次验证属性的资源类型
本文关键字:一次 验证 属性 类型 资源 程序集 定义 | 更新日期: 2023-09-27 18:16:16
目前我正在设置我的域模型,以使用DataAnnotation验证属性,如requiredatattribute和RangeAttribute。
其中一个属性是这样的:
[Required(ErrorMessageResourceType = typeof(ModelValidationMessages), ErrorMessageResourceName = "SurnameRequiredMessage")]
public string Surname { get; set; }
然而,这不是唯一的属性,更不是唯一的模型类。然而,验证消息仅在整个程序集的ErrorMessageResourceType资源类中列出。
问题:
- 是否可以为整个类定义ErrorMessageResourceType属性?
- 是否可以为整个程序集定义ErrorMessageResourceType属性?
- 如果没有,还有其他方法吗?
提前感谢!
您可以编写自定义DataAnnotationsModelValidator
:
public class GlobalResourceTypeResourceDataAnnotationsModelValidator : DataAnnotationsModelValidator<ValidationAttribute>
{
public GlobalResourceTypeResourceDataAnnotationsModelValidator(
ModelMetadata metadata,
ControllerContext context,
ValidationAttribute attribute
)
: base(metadata, context, attribute)
{
if (Attribute.ErrorMessageResourceType == null)
{
Attribute.ErrorMessageResourceType = typeof(ModelValidationMessages);
}
}
}
,然后在Application_Start中,您需要为您使用的每个属性注册一个适配器:
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RequiredAttribute), typeof(GlobalResourceTypeResourceDataAnnotationsModelValidator));
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(StringLengthAttribute), typeof(GlobalResourceTypeResourceDataAnnotationsModelValidator));
...