在c#中验证嵌套类属性

时间:2017-10-25 15:03:07

标签: c# .net-core

我有以下课程:

public class Container
{
    public ContainerDetails Details { get; set; }

    public class ContainerDetails
    {
        [MaxLength(50)]
        public string Name { get; set; }
    }
}
控制器上的

我有:

public async Task<IActionResult> Details([FromBody] Container model)
{
    if (!ModelState.IsValid)
    {
        throw new Error();
    }
    ...
    return Json();
}

和我的ModelState.IsValid始终true

我可以在没有任何自定义代码的情况下验证嵌套类属性吗?如何?或者可能是插件,我可以设置一些属性来验证它?

2 个答案:

答案 0 :(得分:1)

我认为你的代码还可以。您确定要将services.AddMvc()添加到Startup.cs文件中吗?

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
}

答案 1 :(得分:0)

不知道.NET-Core,但我认为这应该有用。但是你必须滚动自己的验证内容并对没有属性验证嵌套对象的每个属性执行递归调用 您还应添加其他属性以标记不应验证的属性,以提高嵌套验证的性能。

public class MaxLengthAttribute: Attribute
{
    public int Length { get; private set; }
    public MaxLengthAttribute(int length)
    {
        Length = length;
    }
}

public class MyData
{
    [MaxLengthAttribute(5)]
    public string Test { get; set; }
}

public static class Validator
{
    public static void Validate(object o)
    {
        // Returns all public properties of the passed object
        var props = o.GetType().GetProperties();
        foreach(var p in props)
        {
            // Check if this current property has the attribute...
            var attrs = p.GetCustomAttributes(typeof(MaxLengthAttribute), false);
            // Recursive call here if you want to validate nested properties
            if (attrs.Length == 0) continue;

            // Get the attribute and its value
            var attr = (MaxLengthAttribute)attrs[0];
            var length = attr.Length;

            // Get the value of the property that has the attribute
            var current = (string)p.GetValue(o, null);

            // perform the validation
            if (current.Length > length)
                throw new Exception();
        }
    }
}