c# - 是否可以将 DataAnnotations 与接口(interface)一起使用?

标签 c# .net data-annotations

我想使用 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/

相关文章:

c# - 如何解决这个位操作?

c# - NMock - 如何使具有相同参数类型的方法返回不同的值?

c# - 具有无效值的 DataAnnotations 消息

asp.net-mvc - MVC数据标注层: where to put the set CurrentUICulture statement?

c# - 如何在不重新编译的情况下更新 C# DLL 的文件版本号?

c# - 如何获取 XElement 的第一个元素

c# - 嵌入式单声道 : How to use 'mono_runtime_invoke' on different thread

c# - 如何模仿Opera 10.50的自定义UI?

.net - IsAjaxRequest 在具有正确 header 的 AngularJs $http.post 上返回 false

javascript - .Net Core 中的自定义属性未显示验证消息