WCF JSON Serialization error with DateTime.MinVal and UTC

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值