我想使用 DataAnnotations 来验证实现某些接口(interface)的类,因此我向接口(interface)添加了验证属性,如下所示:
public interface IUser
{
[Required]
string Name { get; set; }
[Display(Name = "Email Address")]
[Required]
string Email { get; set; }
}
当我尝试使用 Validator.TryValidateObject
时它不起作用。
有什么方法可以做到这一点而不必编写自定义 TryValidateObject
方法?
最佳答案
我很惊讶没有人提到 MetadataTypeAttribute .但是,是的,这行得通。
[MetadataType(typeof(ICustomerMetaData))]
public partial class Customer
{
}
public interface ICustomerMetaData
{
// Apply RequiredAttribute
[Required(ErrorMessage = "Title is required.")]
string Title { get; }
}
至于直接使用接口(interface)(使用Customer: ICustomerMetaData
):
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?
虽然 MVC 会自动将 MetaData 注册到 TypeDescriptor,但您可能需要自己手动添加:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
public class Program
{
public static void Main()
{
var customer = new Customer();
TypeDescriptor.AddProviderTransparent(
new AssociatedMetadataTypeTypeDescriptionProvider(typeof(Customer),
typeof(ICustomerMetaData)),
typeof(Customer));
var context = new ValidationContext(customer);
var validationResults = new List<ValidationResult>();
var isValid = Validator.TryValidateObject(
customer, context, validationResults, true);
Console.WriteLine($"is Valid = {isValid}");
customer.Title = "I has Title";
isValid = Validator.TryValidateObject(
customer, context, validationResults, true);
Console.WriteLine($"is Valid = {isValid}");
Console.ReadKey();
}
[MetadataType(typeof(ICustomerMetaData))]
public partial class Customer
{
public string Title { get; set; }
}
public interface ICustomerMetaData
{
// Apply RequiredAttribute
[Required(ErrorMessage = "Title is required.")]
string Title { get; }
}
}
输出:
is Valid = False
is Valid = True
关于c# - 是否可以将 DataAnnotations 与接口(interface)一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5919567/