是否可以将 DataAnnotations 与接口一起使用?

发布于 2024-11-05 07:41:27 字数 356 浏览 0 评论 0原文

我想使用 DataAnnotations 来验证实现某些接口的类,因此我向接口添加验证属性,如下所示:

public interface IUser
{
    [Required]
    string Name { get; set; }

    [Display(Name = "Email Address")]
    [Required]
    string Email { get; set; }
}

当我尝试使用 Validator.TryValidateObject 时,它不起作用。

有没有办法做到这一点,而不必编写自定义 TryValidateObject 方法?

I want to use DataAnnotations to validate classes that implements some interfaces, and so I'm adding validation attributes to the interface, like this:

public interface IUser
{
    [Required]
    string Name { get; set; }

    [Display(Name = "Email Address")]
    [Required]
    string Email { get; set; }
}

It doesn't work when I try to use Validator.TryValidateObject.

Is there any way to make this instead of having to write a custom TryValidateObject method?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

冰魂雪魄 2024-11-12 07:41:27

我很惊讶没有人提到 MetadataTypeAttribute。但是,是的,这有效。

[MetadataType(typeof(ICustomerMetaData))]
public partial class Customer
{
}


public interface ICustomerMetaData
{
  // Apply RequiredAttribute
  [Required(ErrorMessage = "Title is required.")]
  string Title { get; }
}

至于直接使用接口(使用Customer: ICustomerMetaData):

产品团队不想实现此功能,主要有两个原因:

• 与 DataAnnotations.Validator 的一致性

• 与 ASP.Net MVC 中的验证行为保持一致

• 棘手的场景:一个类实现了两个具有相同属性的接口,但它们的属性存在冲突。哪个属性优先?

虽然 MVC 自动使用 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; }
     }
  }

输出:

有效 = 错误

有效 = True

I'm surprised no one mentioned MetadataTypeAttribute. But yes, this works.

[MetadataType(typeof(ICustomerMetaData))]
public partial class Customer
{
}


public interface ICustomerMetaData
{
  // Apply RequiredAttribute
  [Required(ErrorMessage = "Title is required.")]
  string Title { get; }
}

As for using an Interface directly (using 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?

While MVC automatically registers the MetaData with the TypeDescriptor, you may have to manually add it yourself:

  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; }
     }
  }

Output:

is Valid = False

is Valid = True

沫尐诺 2024-11-12 07:41:27

如果您使用基类而不是接口,则属性将正常工作。

If you use a base class instead of an interface, the attributes will work fine.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文