After digging a little more, I found a way to make this work.
The problem was not so much in the serializer as in the fact that the model dates are not expressed in UTC, but in local time. ASP.Net allows you to create custom model bindings, and I think this is the key to changing dates in UTC after they are deserialized.
I used the following code to make this work, there may be a few errors to smooth out, but you get the idea:
public class UtcModelBinder : DefaultModelBinder { protected override void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, object value) { HttpRequestBase request = controllerContext.HttpContext.Request; // Detect if this is a JSON request if (request.IsAjaxRequest() && request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase)) { // See if the value is a DateTime if (value is DateTime) { // This is double casting, but since it a value type there not much other things we can do DateTime dateValue = (DateTime)value; if (dateValue.Kind == DateTimeKind.Local) { // Change it DateTime utcDate = dateValue.ToUniversalTime(); if (!propertyDescriptor.IsReadOnly && propertyDescriptor.PropertyType == typeof(DateTime)) propertyDescriptor.SetValue(bindingContext.Model, utcDate); return; } } } // Fall back to the default behavior base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value); } }
Jeroen landheer
source share