この問題は、ASP.NETコア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());
...
}
}
この私たちはそれについて考えなくてもいいように、インフラストラクチャーによってうまく処理されるようなものです*毎回* DateTimeを処理します。 –
@DavidBoike:http://www.martin-brennan.com/custom-utc-datetime-model-binding-mvc/ –