【问题标题】:C# DataAnnotation doesn't throw exception when data is invalid?当数据无效时,C# DataAnnotation 不会抛出异常?
【发布时间】:2019-06-06 11:43:04
【问题描述】:

我有一个使用 Data 的非常快速的代码定义:

using System.ComponentModel.DataAnnotations;
class UseDataAnnotations
{
    [Required(ErrorMessage = "Name is compulsory")]
    [StringLength(20)]
    [RegularExpression(@"^[A-Z]{5, 20}$")]
    public string Name { get; set; }
}
class Program
{
    public static void Main(String [] args)
    { 
        UseDataAnnotations obj = new UseDataAnnotations();
        obj.Name = null;
        var context = new ValidationContext(obj, null, null);
        var result = new List<ValidationResult>();
        bool IsValid = Validator.TryValidateObject(
            obj, 
            context,
            null, 
            true);
        Console.WriteLine(IsValid);
        foreach(var x in result)
        {
            Console.WriteLine(x.ErrorMessage);
        }
    }
}

我希望:只要“名称”字段为空,所有检查都应该失败并抛出某种异常。

但是在运行这个程序时,它只是打印“False”,没有其他任何事情发生。那么我在哪里出错了,我的“DataAnnotation”是否有效?

我正在使用 vs2017。非常感谢。

【问题讨论】:

    标签: c# exception annotations


    【解决方案1】:

    验证工作正常,您可以按预期获得false,但是您没有通过TryValidateObject 方法上的result 来填充错误。示例:

    UseDataAnnotations obj = new UseDataAnnotations();
    obj.Name = null;
    
    var context = new ValidationContext(obj, null, null);
    var result = new List<ValidationResult>();
    
    // pass the result here as the argument to fill it up with the erros.
    bool IsValid = Validator.TryValidateObject(obj, context, result, true);
    
    Console.WriteLine(IsValid);
    
    foreach(var x in result)
    {
        Console.WriteLine(x.ErrorMessage);
    }
    

    在此处查看工作示例:https://dotnetfiddle.net/lI3z1M

    【讨论】:

      猜你喜欢
      • 2019-04-13
      • 2013-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-11
      • 1970-01-01
      • 2013-11-29
      • 2014-02-23
      相关资源
      最近更新 更多