簡體   English   中英

使用MVC外部的DataAnnotations自動進行模型驗證

[英]Automatic Model Validation using DataAnnotations outside MVC

我正在使用DataAnnotation屬性將驗證應用於MVC之外的模型上的屬性。

public class MyModel
{
    [Required]
    [CustomValidation]
    public string Foo { get; set; }
}

我已經實現了以下擴展方法來驗證模型。

public static void Validate(this object source)
{
    if (source == null)
        throw new ArgumentNullException("source");

    var results = new List<ValidationResult>();
    bool IsValid = Validator.TryValidateObject(source, new ValidationContext(source, null, null), results, true);
    if (!IsValid)
        results.ForEach(r => { throw new ArgumentOutOfRangeException(r.ErrorMessage); });
 }

每次設置不方便的屬性時,我都必須調用此Validate()方法:

MyModel model = new MyModel();
model.Foo = "bar";
model.Validate();

model.Foo = SomeMethod();
model.Validate();

我希望在模型狀態更改時在后台自動調用Validate()方法。 是否有人對如何實現這一目標有任何想法?

對於獎勵積分,沒有人確切知道MVC如何通過DataAnnotations實現此自動驗證嗎?

謝謝。

您可以在每次setter調用之后使用proxies包裝類,攔截屬性setter和驗證對象。 對於Castle DynamicProxy,這將是:

public class ValidationInterceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        invocation.Proceed();

        if (invocation.Method.IsSpecialName && invocation.Method.Name.StartsWith("set_"))
        {
            invocation.InvocationTarget.Validate();
        }
    }
}

然后,您將使用DynamicProxy而不是new運算符創建模型:

ProxyGenerator proxyGenerator = new ProxyGenerator();
MyModel model = proxyGenerator.CreateClassProxy<MyModel>(new ValidationInterceptor());

model.Foo = "bar";

model.Foo = SomeMethod();

重要的是MyModel的所有屬性都必須是虛擬的,以便代理工作:

public class MyModel
{
    public virtual string Foo { get; set; }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM