我有以下的定制要求的属性:用C#和Web API,并使用与验证方面的私人访问修饰符定制所需的属性
public class RequiredIfAttribute : RequiredAttribute
{
private string _DependentProperty;
private object _TargetValue;
public RequiredIfAttribute(string dependentProperty, object targetValue)
{
this._DependentProperty = dependentProperty;
this._TargetValue = targetValue;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var propertyTestedInfo = validationContext.ObjectType.GetProperty(this._DependentProperty);
if (propertyTestedInfo == null)
{
return new ValidationResult(string.Format("{0} needs to be exist in this object.", this._DependentProperty));
}
var dependendValue = propertyTestedInfo.GetValue(validationContext.ObjectInstance, null);
if (dependendValue == null)
{
return new ValidationResult(string.Format("{0} needs to be populated.", this._DependentProperty));
}
if (dependendValue.Equals(this._TargetValue))
{
var x = validationContext.ObjectType.GetProperty("_Mappings");
var objectInstance = (Dictionary<object, string[]>)x.GetValue(validationContext.ObjectInstance, null);
var isRequiredSatisfied = false;
foreach (var kvp in objectInstance)
{
if (kvp.Key.Equals(this._TargetValue))
{
foreach (var field in kvp.Value)
{
var fieldValue = validationContext.ObjectType.GetProperty(field).GetValue(validationContext.ObjectInstance, null);
if (fieldValue != null && field.Equals(validationContext.MemberName))
{
isRequiredSatisfied = true;
break;
}
}
}
}
if (isRequiredSatisfied)
{
return ValidationResult.Success;
}
else
{
return new ValidationResult(string.Empty);
}
}
else
{
// Must be ignored
return ValidationResult.Success;
}
}
}
我所试图实现与那就是我想要有条件验证基于在模型中的属性上。它还需要足够通用以在多个模型上重复使用。当一个指定的属性具有特定的值(我在属性中指定)时,自定义所需的验证需要匹配这些值。例如,在这个模型中:
public class PaymentModel
{
public Dictionary<object, string[]> _Mappings
{
get
{
var mappings = new Dictionary<object, string[]>();
mappings.Add(true, new string[] { "StockID" });
mappings.Add(false, new string[] { "Amount" });
return mappings;
}
}
[Required]
public bool IsBooking { get; set; }
[RequiredIfAttribute("IsBooking", false)]
public decimal? Amount { get; set; }
[RequiredIf("IsBooking", true)]
public int? StockID { get; set; }
public PaymentModel()
{
}
}
如果IsBooking
属性为true
,那么我想StockId
被必需的,但如果是false
,然后Amount
应符合规定。
目前的解决方案,我有工作,但它有2个问题:
- 上有
_Mappings
财产,我想不会有依赖性。有谁知道我会如何绕过我的方式? - 如果我必须使用
_Mappings
属性,是否有任何方法可以将它用作private
访问修饰符?目前我只能使我的解决方案工作,如果_Mappings
是public
,因为validationContext.ObjectType.GetProperty("_Mappings")
找不到private
修饰符。 (如果我想在Web API响应中将此模型序列化为JSON,那么理想情况下我不希望将验证映射发送出去。)
谢谢马丁。你是完全正确的,我试图把它复杂化。 – Ebbs