我需要为StringLengthAttribute
现有 ASP.NET MVC 4 项目中的许多模型添加验证,并尝试通过我自己的模型元数据提供程序自动执行此操作,该提供程序源自DataAnnotationsModelMetadataProvider
.
它与其他一些数据注释属性完美配合RequiredAttribute
(我让客户端和服务器端验证都工作),但是没有添加对字符串长度的验证 - 找到下面的最小示例。
public class CustomModelMetadataProvider : DataAnnotationsModelMetadataProvider
{
protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes,
Type containerType,
Func<object> modelAccessor,
Type modelType,
string propertyName)
{
StringLengthAttribute lengthAttribute = new StringLengthAttribute(256);
attributes = attributes.Union(new[] { lengthAttribute });
return base.CreateMetadata(attributes,
containerType,
modelAccessor,
modelType,
propertyName);
}
}
所以,看起来StringLengthAttribute
它正在以某种特殊的方式处理。关于如何使其工作或更好的实施想法的任何想法?