首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何告诉ASP.Net MVC,从JSon反序列化的所有传入日期都应该是UTC?

如何告诉ASP.Net MVC,从JSon反序列化的所有传入日期都应该是UTC?
EN

Stack Overflow用户
提问于 2012-03-02 20:49:01
回答 1查看 1.8K关注 0票数 8

我用UTC格式从我的web应用程序中发送日期,但是当我在服务器端收到它们时,JSon序列化程序(可能是通过设置模型来使用)在本地日期和时间中使用相对于服务器时区的DateTimeKind.Local。

当我执行DateTime.ToUniversalTime()时,我得到了正确的UTC日期,所以这不是一个问题。转换工作正常,日期以应有的方式发送.但是..。我不喜欢在我的模型上的每一个日期调用“ToUniversalTime()”,然后再将它存储到数据库中.这容易出错,很容易忘记当你有一个大的应用程序。

因此,问题是:有没有办法告诉MVC,传入的日期应该总是以UTC格式表示?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-03-02 22:17:34

在深入挖掘之后,我找到了一种方法来完成这个任务。

问题不在于序列化程序,而在于模型的日期不是以UTC表示,而是在本地时间表示。ASP.Net允许您创建自定义模型绑定程序,我认为这是在反序列化之后将日期更改为UTC的关键。

我使用了下面的代码来完成这项工作,可能会有一些bug需要解决,但是您会有这样的想法:

代码语言:javascript
复制
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);

  }
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9540149

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档