Este problema persiste en ASP.NET Core 2.0. El siguiente código lo resolverá, admitiendo los formatos básicos y extendidos ISO 8601, conservando correctamente el valor y configurando DateTimeKind
correctamente. Esto se alinea con el comportamiento predeterminado del análisis de JSON.Net, por lo que mantiene el comportamiento de enlace de su modelo alineado con el resto del sistema.
En primer lugar, añadir el siguiente modelo de aglutinante:
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;
}
}
A continuación, añada el siguiente proveedor de modelo de ligante:
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));
}
}
luego registrar el proveedor en su archivo Startup.cs
:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
...
options.ModelBinderProviders.Insert(0, new DateTimeModelBinderProvider());
...
}
}
Este es el tipo de cosa que sería mejor manejada por la infraestructura, así que no tenemos que pensar en ello * cada vez * manejamos un DateTime. –
@DavidBoike: http://www.martin-brennan.com/custom-utc-datetime-model-binding-mvc/ –