Asp.net网页API嵌套模型验证 [英] Asp.net Web Api nested model validation

查看:121
本文介绍了Asp.net网页API嵌套模型验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要有点问题的运行在asp.net网页API的模型绑定和验证(通过数据注解)。

I'm running in to a bit of a problem in asp.net web api's model binding and validation (via data annotations).

这似乎是,如果我有属性的模型,如

It seems like if i have a model with property such as

Dictionary<string, childObject> obj { get; set; }

在childObject的验证似乎并没有触发。该数据是从JSON绑定Json.Net串行器。

the childObject's validations don't seem to trigger. The data is bound from json with Json.Net serializer.

有一些解决办法或修复这样做呢?还是我误解了别的东西与此有关?

Is there some workaround or fix to this? Or have I misunderstood something else related to this?

我不禁想知道为什么这不会导致错误:

I can't help but wonder why this doesn't result in errors:

public class Child
{        
    [Required]
    [StringLength(10)]
    public string name;
    [Required]
    [StringLength(10)]
    public string desc;     
}

//elsewhere
Child foo = new Child();
foo.name = "hellowrodlasdasdaosdkasodasasdasdasd";

List<ValidationResult> results = new List<ValidationResult>();
Validator.TryValidateObject(foo, new ValidationContext(foo), results, true);
// results.length == 0 here.


天啊。我忘了申报,而不是域属性。


Oh god. I had forgotten to declare properties instead of fields.

推荐答案

有2种方式,你可以在字典值设置验证。如果你不关心让所有的错误,但只是第一个遇到的,你可以使用自定义的验证属性。

There are 2 ways you can setup validation of the Dictionary Values. If you don't care about getting all the errors but just the first one encountered you can use a custom validation attribute.

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

    [ValidateDictionary]
    public Dictionary<string, Bar> BarInstance { get; set; }
}

public class Bar
{
    [Required]
    public string BarRequiredProperty { get; set; }
}

public class ValidateDictionaryAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (!IsDictionary(value)) return ValidationResult.Success;

        var results = new List<ValidationResult>();
        var values = (IEnumerable)value.GetType().GetProperty("Values").GetValue(value, null);
        values.OfType<object>().ToList().ForEach(item => Validator.TryValidateObject(item, new ValidationContext(item, null, validationContext.Items), results));
        Validator.TryValidateObject(value, new ValidationContext(value, null, validationContext.Items), results);
        return results.FirstOrDefault() ?? ValidationResult.Success;
    }

    protected bool IsDictionary(object value)
    {
        if (value == null) return false;
        var valueType = value.GetType();
        return valueType.IsGenericType && valueType.GetGenericTypeDefinition() == typeof (Dictionary<,>);
    }
}

另一种方法是创建自己的字典为 IValidatableObject 并做验证在。该解决方案为您提供了返回所有错误的能力。

The other way is to create your own Dictionary as an IValidatableObject and do the validation in that. This solution gives you the ability to return all the errors.

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

    public ValidatableDictionary<string, Bar> BarInstance { get; set; }
}

public class Bar
{
    [Required]
    public string BarRequiredProperty { get; set; }
}

public class ValidatableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IValidatableObject
{
    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        var results = new List<ValidationResult>();
        Values.ToList().ForEach(item => Validator.TryValidateObject(item, new ValidationContext(item, null, validationContext.Items), results));
        return results;
    }
}

这篇关于Asp.net网页API嵌套模型验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆