此问题在 ASP.NET Core 2.0 中仍然存在。以下代码将解决它,支持 ISO 8601 基本和扩展格式,正确保留值并DateTimeKind
正确设置。这与 JSON.Net 解析的默认行为一致,因此它使您的模型绑定行为与系统的其余部分保持一致。
首先,添加以下模型绑定器:
public class DateTimeModelBinder : IModelBinder
{
private static readonly string[] DateTimeFormats = { "yyyyMMdd'T'HHmmss.FFFFFFFK", "yyyy-MM-dd'T'HH:mm:ss.FFFFFFFK" };
public Task BindModelAsync(ModelBindingContext bindingContext)
{
if (bindingContext == null)
throw new ArgumentNullException(nameof(bindingContext));
var stringValue = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).FirstValue;
if (bindingContext.ModelType == typeof(DateTime?) && string.IsNullOrEmpty(stringValue))
{
bindingContext.Result = ModelBindingResult.Success(null);
return Task.CompletedTask;
}
bindingContext.Result = DateTime.TryParseExact(stringValue, DateTimeFormats,
CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var result)
? ModelBindingResult.Success(result)
: ModelBindingResult.Failed();
return Task.CompletedTask;
}
}
然后添加以下模型绑定器提供程序:
public class DateTimeModelBinderProvider : IModelBinderProvider
{
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
if (context == null)
throw new ArgumentNullException(nameof(context));
if (context.Metadata.ModelType != typeof(DateTime) &&
context.Metadata.ModelType != typeof(DateTime?))
return null;
return new BinderTypeModelBinder(typeof(DateTimeModelBinder));
}
}
然后在您的Startup.cs
文件中注册提供程序:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
...
options.ModelBinderProviders.Insert(0, new DateTimeModelBinderProvider());
...
}
}