您的问题可以通过自定义model binding 解决,这是cross-cutting concerns 的一种。 cross-cutting concerns 的想法是在管道中找到一个共同的可扩展点,以注入一些代码来做某事,而无需在任何地方重复或传播代码。所以在这里你可以使用一个自定义的IModelBinder,它应该总是有效的。但是,按照 Microsoft 的建议,在这种情况下,您有一个 DateTime 的字符串表示形式,您需要将其转换为 DateTime。这应该使用TypeConverter 来完成,这比使用自定义IModelBinder 更简单。您可以为您的DateTime 字符串(从查询字符串、路由数据...获取)创建自定义TypeConverter,以处理DateTime 的某些特定格式。
这里只是一个例子:
public class CustomDateTimeConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return typeof(DateTime?).IsAssignableFrom(destinationType) || base.CanConvertTo(context, destinationType);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
//your custom logic to parse a DateTime from your specific format here
//For a simple and funny example, I use the word "today"
if(value?.ToString() == "today")
{
return DateTime.Today;
}
return base.ConvertFrom(context, culture, value);
}
}
现在您需要为DateTime 注册这个自定义类型转换器,例如在Startup.cs 中的ConfigureServices 方法中(也可以放在静态方法中):
TypeDescriptor.AddAttributes(typeof(DateTime), new TypeConverterAttribute(typeof(CustomDateTimeConverter)));
现在假设您的模型属性(DateTime 或 DateTime?)名称为 Date,以下查询字符串应将 DateTime.Today 发送到您的模型属性:
?date=today