在MVC之外使用ASP.Net MVC数据注释

Dou*_*oug 20 c# asp.net-mvc class-library data-annotations

我想知道是否有一种方法可以在没有MVC网站的情况下使用ASP.Net的数据注释.

我的例子是我有一个曾经创建过的类需要验证,否则会抛出错误.我喜欢数据注释方法,而不是initaliser发出的一堆if块.

有没有办法让这个工作?

我以为它会是这样的:

  • 添加数据注释
  • 在初始化器中触发一个方法,该方法在类上调用MVC验证器

有任何想法吗?我必须承认我没有将MVC框架添加到我的项目中,因为我希望我可以使用数据注释类System.ComponentModel.DataValidation

Dar*_*rov 30

这是一个例子:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

public class Foo
{
    [Required(ErrorMessage = "the Bar is absolutely required :-)")]
    public string Bar { get; set; }
}

class Program
{
    public static void Main()
    {
        var foo = new Foo();
        var results = new List<ValidationResult>();
        var context = new ValidationContext(foo, null, null);
        if (!Validator.TryValidateObject(foo, context, results))
        {
            foreach (var error in results)
            {
                Console.WriteLine(error.ErrorMessage);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但说实话,FluentValidation更强大.

  • 我在寻找.Net 3.5解决方案 - 在.Net 4.0之前无法使用ValidationContext (3认同)
  • 在我的例子中,对`TryValidateObject`的调用只会检查`RequiredAttribute`.如果你想使用`System.ComponentModel.DataAnnotations`中的其他验证器,比如`MaxLengthAttribute`,为第四个参数添加`true`(`validateAllProperties`).请参阅/sf/ask/375807071/上接受的答案 (2认同)