C# 如何检查自定义模型绑定器中的特性属性
我希望强制我的系统中的所有日期都是有效的,而不是将来的日期,因此我在自定义模型绑定器中强制执行这些日期:C# 如何检查自定义模型绑定器中的特性属性,c#,asp.net-mvc,model-binding,C#,Asp.net Mvc,Model Binding,我希望强制我的系统中的所有日期都是有效的,而不是将来的日期,因此我在自定义模型绑定器中强制执行这些日期: class DateTimeModelBinder : IModelBinder { public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { var value = bindingContext.ValueProvider.Ge
class DateTimeModelBinder : IModelBinder {
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
try {
var date = value.ConvertTo(typeof(DateTime), CultureInfo.CurrentCulture);
// Here I want to ask first if the property has the FutureDateAttribute
if ((DateTime)date > DateTime.Today) {
bindingContext.ModelState.AddModelError(bindingContext.ModelName, "No se puede indicar una fecha mayor a hoy");
}
return date;
}
catch (Exception) {
bindingContext.ModelState.AddModelError(bindingContext.ModelName, "La fecha no es correcta");
return value.AttemptedValue;
}
}
}
现在,对于一些例外情况,我想允许一些日期在未来
[Required]
[Display(Name = "Future Date")]
[DataType(DataType.DateTime)]
[FutureDateTime] <-- this attribute should allow the exception
public DateTime FutureFecha { get; set; }
现在,问题是:如何检查属性是否存在于BindModel
方法中?在绑定模型属性期间,我们可以通过以下方式访问属性所有者:
bindingContext.ModelMetadata.ContainerType
因此,下面的代码片段应该为FutureFecha属性将变量hasAttribute
设置为true
var holderType=bindingContext.ModelMetadata.ContainerType;
if(holderType!=null)
{
var propertyType=holderType.GetProperty(bindingContext.ModelMetadata.PropertyName);
var attributes=propertyType.GetCustomAttributes(true);
var hasaAttribute=属性
.Cast()
.Any(a=>a.GetType().IseEquivalentto(typeof(FutureDateTime)));
如果(hasAttribute)。。。
}
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class FutureDateTimeAttribute : Attribute {
}
var holderType = bindingContext.ModelMetadata.ContainerType;
if (holderType != null)
{
var propertyType = holderType.GetProperty(bindingContext.ModelMetadata.PropertyName);
var attributes = propertyType.GetCustomAttributes(true);
var hasAttribute = attributes
.Cast<Attribute>()
.Any(a => a.GetType().IsEquivalentTo(typeof (FutureDateTime)));
if(hasAttribute) ...
}