【问题标题】:How to get argument value in custom validation attribute in .net core 2.1如何在.net core 2.1的自定义验证属性中获取参数值
【发布时间】:2020-08-28 20:40:42
【问题描述】:

我如何从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;
    }
}

【问题讨论】:

    标签: c# asp.net-core asp.net-core-mvc asp.net-core-2.1


    【解决方案1】:

    使用下面的语句来获取它的值:

    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;
        }
    

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

    【讨论】:

    • 太棒了!如果你不介意的话,还有一个小问题。我可以使用myargument 变量名直接获取值还是必须使用索引号?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-04
    • 1970-01-01
    • 2019-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-13
    相关资源
    最近更新 更多