我用UTC格式从我的web应用程序中发送日期,但是当我在服务器端收到它们时,JSon序列化程序(可能是通过设置模型来使用)在本地日期和时间中使用相对于服务器时区的DateTimeKind.Local。
当我执行DateTime.ToUniversalTime()时,我得到了正确的UTC日期,所以这不是一个问题。转换工作正常,日期以应有的方式发送.但是..。我不喜欢在我的模型上的每一个日期调用“ToUniversalTime()”,然后再将它存储到数据库中.这容易出错,很容易忘记当你有一个大的应用程序。
因此,问题是:有没有办法告诉MVC,传入的日期应该总是以UTC格式表示?
发布于 2012-03-02 22:17:34
在深入挖掘之后,我找到了一种方法来完成这个任务。
问题不在于序列化程序,而在于模型的日期不是以UTC表示,而是在本地时间表示。ASP.Net允许您创建自定义模型绑定程序,我认为这是在反序列化之后将日期更改为UTC的关键。
我使用了下面的代码来完成这项工作,可能会有一些bug需要解决,但是您会有这样的想法:
public class UtcModelBinder : DefaultModelBinder
{
protected override void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, object value)
{
HttpRequestBase request = controllerContext.HttpContext.Request;
// Detect if this is a JSON request
if (request.IsAjaxRequest() &&
request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
{
// See if the value is a DateTime
if (value is DateTime)
{
// This is double casting, but since it's a value type there's not much other things we can do
DateTime dateValue = (DateTime)value;
if (dateValue.Kind == DateTimeKind.Local)
{
// Change it
DateTime utcDate = dateValue.ToUniversalTime();
if (!propertyDescriptor.IsReadOnly && propertyDescriptor.PropertyType == typeof(DateTime))
propertyDescriptor.SetValue(bindingContext.Model, utcDate);
return;
}
}
}
// Fall back to the default behavior
base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value);
}
}https://stackoverflow.com/questions/9540149
复制相似问题