For the latest project at work we decided to try out Azure Mobile Services for our backend needs. It’s a simple one-controller backend that stores objects in DocumentDb storage and passes data along. If you haven’t checked out DocumentDb yet, it’s a NoSQL database-as-a-service from Microsoft, hosted in Azure.
The development went smooth, no real trouble and Visual Studio is really an amazing environment, but we stumbled upon one issue with DateTimeOffsets and timezones. When posting to our Web API we had a DateTimeOffset that included timezone information, but when it reached the Post-method in the controller it was converted to UTC automagically. This is something we would want if the data is being stored and passed back to clients which handles timezone conversion gracefully. In our case we want to preserve the date and time as is with the correct timezone as we’re passing this data along to other services such as sending text messages using Twilio.
To disable the conversion to UTC open up the WebApiConfig class and in the Register method add these three lines:
config.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind;
config.Formatters.JsonFormatter.SerializerSettings.DateFormatHandling = DateFormatHandling.IsoDateFormat;
config.Formatters.JsonFormatter.SerializerSettings.DateParseHandling = DateParseHandling.DateTimeOffset;
This configures the JSON serializer to preserve the timezone information (RoundtripKind), and that we explicity set IsoDateFormat (although this is default if I recall correctly, might just omit that), and the last one tells the JSON serializer to convert dates to DateTimeOffset. If you use DateTime then ignore this setting.
With these settings in place we preserve the data as is across the wire.