我正在将一个对象发布到 MVC 控制器。该对象包含一个名为 StartDt 的字段,在客户端上它是本地时间的 javascript Date 对象。
当我对对象调用 JSON.stringify 并使用 jQuery 的 ajax 方法将其 POST 到服务器时,我可以在 Firebug 中看到发送到服务器的 ISO 字符串,如“1900-12-31T13:00:00.000Z”,我将其相信应该是 UTC 格式的当地时间。
但当我查看控制器中的 DateTime 字段时,它看起来像是回到本地时间而不是 UTC。我怎样才能解决这个问题?
我想存储来自客户端的日期的 UTC 版本。
此问题在 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
file:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
...
options.ModelBinderProviders.Insert(0, new DateTimeModelBinderProvider());
...
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)