Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
382 views
in Technique[技术] by (71.8m points)

c# - ServiceStack - Is there a way to force all serialized Dates to use a specific DateTimeKind?

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.

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

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

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

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?)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

Force all serialized DateTimes to be interpreted as UTC

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

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);
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...