c# 特性同时使用到两个属性

292 阅读1分钟

特性里需要同时使用到两个属性,记录此方法。

public class TestAttribute : ValidationAttribute
    {
        private readonly string _test;
        public TestAttribute(string test)
        {
            _test = test;
        }
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            try
            {
                var password = value.ToString();
                var property = validationContext.ObjectType.GetProperty(_test);
                if (property == null)
                {
                    return new ValidationResult($"Unknown property: {_test}");
                }
                var test = property.GetValue(validationContext.ObjectInstance, null).ToString();
                if (test== "xx" && password.IsNullOrEmpty())
                {
                    var error = new
                    {
                        Content = $"Password not exist."
                    };
                    return new ValidationResult(JsonConvert.SerializeObject(error));
                }
                return ValidationResult.Success;
            }
            catch (Exception e)
            {
                return new ValidationResult(e.Message);
            }
        }
    }