本文介绍了ServiceStack - 有没有办法强制所有序列日期为使用特定DateTimeKind?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个POCO这样的:

I have a POCO like this:

public class BlogEntry
{
    public string Title { get; set; }
    public DateTime Date { get; set; }
}



大多数它正在从实体框架水合的时间,但它可以和将实体框架之外使用。

Most of the time it's being hydrated from Entity Framework, but it can and will be used outside of Entity Framework.

DateTimeKind从EF日期是不确定的,这从我读的是正常的。

The DateTimeKind for the Date from EF is Unspecified, which from what I read is normal.

当我缓存此POCO在Redis的(使用ServiceStack Redis的客户端),它回来了当地的DateTimeKind。

When I cache this POCO in Redis (using the ServiceStack Redis client), it comes back with a DateTimeKind of Local.

因此,有一个抖动在返回的对象。第一遍(非高速缓存)的ISO-8061没有偏移(DateTimeKind.Unspecified)。第二阶段(缓存)是ISO-8061具有偏移(从Redis的与DateTimeKind.Local)。

So there is a jitter with the returned objects. The first pass (uncached) has ISO-8061 with no offset (DateTimeKind.Unspecified). The second pass (cached) is ISO-8061 with an offset (from Redis with DateTimeKind.Local).

任何方式强迫ServiceStack JSON序列总是解释为日期一个给定的DateTimeKind? (我知道有一个JsConfig.AppendUtcOffset属性,但它是否是真的还是假的,值永远不会改变我?)

Any way to force the ServiceStack JSON serializer to always interpret dates as a given DateTimeKind? (I know there is a "JsConfig.AppendUtcOffset" property, but whether it's true or false, the values never change for me?)

或介于反序列化过程从我输入RedisClient使DateTimeKind地方?

Or somewhere in the deserialization process from my typed RedisClient to make the DateTimeKind local?

我可以手动改变我的POCO的强制执行DateTimeKind - 这作品 - 但我希望的东西不容易出错。

I can manually change my POCO's to enforce the DateTimeKind - and that works - but I was hoping for something less error prone.

推荐答案

如果你需要比@ mythz的回答更多的东西可配置的,可以强制创建DateTime对象的序列化和反序列化有一定的 DateTimeKind 通过覆盖DateTime和可选的DateTime?序列和/或反串行化的方法。

If you need something more configurable than @mythz's answer, you can force the serialization or deserialization of DateTimes to have a certain DateTimeKind by overriding the DateTime and optionally DateTime? serialization and/or deserialization methods.

强制所有序列DateTime对象应被解释为UTC

Force all serialized DateTimes to be interpreted as UTC

JsConfig<DateTime>.SerializeFn = time => new DateTime(time.Ticks, DateTimeKind.Local).ToString();

您就可以借此一步越走越错误在反序列化,如果日期时间是不是在指定格式。我开始使用这个时候想强制客户端指定的所有请求的时区,但并不一定要求它永远是UTC。

You can then take this one step farther and error on deserialization if the DateTime isn't in a specified format. I started using this when I wanted to force clients to specify the timezone in all requests, but not necessarily require that it always be Utc.

JsConfig<DateTime>.DeSerializeFn = time =>
{
  if (!IsInCorrectDateFormat(time))
    throw new System.Runtime.Serialization.SerializationException(BadDateTime);

  return ServiceStack.Text.Common.DateTimeSerializer.ParseDateTime(time);
};

这篇关于ServiceStack - 有没有办法强制所有序列日期为使用特定DateTimeKind?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 14:09