您的位置:首页 > Web前端 > JavaScript

WCF JSON Serialization error with DateTime.MinVal and UTC

2014-04-01 13:45 453 查看
I came across the following error today in is WCF JSON web service:

SerializationException: DateTime values that are greater than DateTime.MaxValue or smaller than DateTime.MinValue when converted to UTC cannot be serialized to JSON.
The solution took me a while to get my head round, so I thought I should share it. The clue was a StackOverflow post specifying
the error and its cause.

This was compounded by the fact that the WCF service was returning a rather obscure 504 error, namely:

ReadResponse() failed: The server did not return a response for this request.
The error was not being picked up and returned as a service fault, so I switched WCF tracing on. The error message was then visible in the logs:

<Exception>
<ExceptionType>System.Runtime.Serialization.SerializationException, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType>
<Message>DateTime values that are greater than DateTime.MaxValue or smaller than DateTime.MinValue when converted to UTC cannot be serialized to JSON.</Message>


The bottom line is that if you have a DateTime property that is not set, it will be defaulted to DateTime.MinVal when serialized. However, DateTime.MinVal does not have a DateTimeKind specified,
which is the default.

This causes a problem with the serializer because it does not treat the MinVal as UTC. If you are in a timezone + GMT (East), then this is going to cause you a problem,
and you'll get the error above. This is very nicely described by Adam Robinson:

If your time zone is GMT+1, then the UTC value of DateTime.MinValue in your time zone is going to be an hour less than DateTime.MinValue.
In my case I had a bunch of DTO objects being passed back as JSON. The serializer would hit the defaulted DateTime value and error. the solution was simple:

foreach (var dto in dtos)
{
dto.DateStart = DateTime.SpecifyKind(dto.DateStart, DateTimeKind.Utc);
}


The alternative is to stop DateTimes being left empty. In my case an Automapper misconfiguration
on the developer's part. If you have the potential for empty DateTime properties, then maybe consider making them nullable.
http://benpowell.soup.io/post/156011793/WCF-JSON-Serialization-error-with-DateTime-MinVal
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: