none
用Validator验证数据后执行TypeDescriptor.RemoveProvider无效? RRS feed

  • 问题

  • 首先给要验证的类绑定关联类,验证之后移除关联类。但是现在遇到的问题是,当执行完 Validator.TryValidate方法后,移除关联类的代码无效了,下次换另一种MetadataType进行关联验证的时候,还是会跑到第一次绑定的关联类中指定的CustomValidation方法中,请问怎样才能多次绑定不同的关联类?

    代码如下:

    public static string ValidateModel<MetadataType>(this object instance) { var targetType = instance.GetType(); var typeProvider = new AssociatedMetadataTypeTypeDescriptionProvider(targetType, typeof(MetadataType)); try { if (targetType != typeof(MetadataType)) { TypeDescriptor.AddProvider(typeProvider, targetType);

    //如果在此处进行移除,后面的验证方法就不再触发。

    //但如果在验证方法执行之后再移除,下次验证的地方还是会触发首次绑定的方法。 //TypeDescriptor.RemoveProvider(typeProvider, targetType); } var validationContext = new ValidationContext(instance, null, null); var validationResults = new List<ValidationResult>(); bool result = Validator.TryValidateObject(instance, validationContext, validationResults); if (validationResults.Count > 0) { return validationResults.First().ErrorMessage; } else { return string.Empty; } } catch (Exception ex) { return ex.Message; } finally { TypeDescriptor.RemoveProvider(typeProvider, targetType); } }


    2016年2月1日 9:26

答案

  • 您好 Runerback,

    TypeDescriptor用于将类模型和类的元数据进行分离,我们需要为类加上一个特性指定定义该类元数据的类。

    [MetadataType(typeof(ResourceMetadata))]

    >> 请问怎样才能多次绑定不同的关联类?

    AssociatedMetadataTypeTypeDescriptionProvider并不适用去这种场合。 由于您需要对同一个模型使用多种模式的验证。我建议您使用以下方法。 把模型对象转换为可验证对象后再进行验证。

    public class Student
    {
        public string Name { get; set; }
    
        public int Age { get; set; }
    }
    
    public class ValidateStudent1 
    {
        private Student _student = null;
    
        public ValidateStudent1(Student student)
        {
            _student = student;
        }
        
        [Range(1,100)]
        public int Age { get { return _student.Age; } }
    }
    
    public class ValidateStudent2
    {
        private Student _student = null;
    
        public ValidateStudent2(Student student)
        {
            _student = student;
        }
    
        [StringLength(20)]
        public string Name { get { return _student.Name; } }
    }
    


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    2016年2月3日 2:08
    版主