如何在.net core 2.1 的自定义验证属性中获取参数值

How to get argument value in custom validation attribute in .net core 2.1

如何从 ValidateMain

访问 myargumentargvalue

型号

[ValidateMain]
public class MainClass
{
    [ValidateChild(myargument: "argvalue")]
    public string myproperty { get; set; }

    [ValidateChild(myargument: "argvalue2")]        
    public string myproperty2 { get; set; }

}

验证属性

public class ValidateChild : ValidationAttribute
{
    private readonly string myargument;

    public ValidateChild(string myargument)
    {
        this.myargument = myargument;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        // Here I know how to get myargument value. My problem is how to get it in ValidateMain
        return ValidationResult.Success;
    }
}

public class ValidateMain : ValidationAttribute
{
    public ValidateMain()
    {

    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        foreach (System.Reflection.PropertyInfo item in value.GetType().GetProperties())
        {
            // What I need here is to get 'myargument' value 'argvalue'
        }
        return ValidationResult.Success;
    }
}

使用以下语句获取其值:

protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        foreach (System.Reflection.PropertyInfo item in value.GetType().GetProperties())
        {
            var x = item.CustomAttributes.FirstOrDefault().ConstructorArguments.FirstOrDefault();

        }
        return ValidationResult.Success;
    }

调试并快速观看然后您就可以了解如何获得它