Saving a toISODate gets deserialized as a non-iso string

帅比萌擦擦* 提交于 2019-12-12 06:36:43

问题


I follow the usual recommendations of serializing javascript Date objects to be sent to the server by using the toISODate js function.

In fact Breeze.js is doing this for me which is great. Everything works as expected when the property on my Entity is a DateTime - the date gets saved to the database as a UTC (0 offset date) datetime.

I hit a problem when the property on the Entity is of type string. A date that is sent over the wire as '2013-06-08T23:00:00Z' is being deserialized into the string property on the Entity as '06/08/2013 23:00:00' and this is the same value that is saved into the varchar backing column in the database.

So the date is being deserialized into a 'en-US' formatted date (MM/dd/yyyy HH:mm:ss). I'm stuck as to why this is happening or how to change things so that the string remains intact as it's deserialized into a string property.

A few technical notes:

  • I confirmed the deserialized value in the property by wiring up a BeforeSaveEntitiesDelegate to the EFContextProvider and inspected the Entity instance in the debugger just before it was saved
  • when inspecting the entity in the BeforeSaveEntitiesDelegate method on the server, I noted that the Thread.CurrentThread.CurrentCulture and CurrentUICulture were both 'en-GB'
  • for technical reasons I need to use a string property rather than a DateTime (or DateTimeOffset) - basically the property could receive any type of data so string is the universal format that will fit everything.

Help would be most welcome!

Thanks Christian Crowhurst


回答1:


For a .NET server, Breeze uses JSON.net to serialize/deserialize json. Breeze allows you to configure this by automatically detecting any 'custom' implementations of the 'BreezeConfig' class.

This means that you can customize Breeze's use of JSON.Net's serialization behavior by implementing a subclass of BreezeConfig. This might look something like this within your server project.

using Breeze.ContextProvider;
using Breeze.WebApi2;
using Newtonsoft.Json;

namespace Sample_WebApi2 {

  public class CustomBreezeConfig : BreezeConfig {

  /// <summary>
  /// Override to use a specialized JsonSerializer implementation.
  /// </summary>
  protected override JsonSerializerSettings CreateJsonSerializerSettings() {
    // get the breeze default settings.
    var baseSettings = base.CreateJsonSerializerSettings();
    // Not sure if this is the setting you want but...
    baseSettings.DateParseHandling = DateParseHandling.None;
    return baseSettings;
  }
}


来源:https://stackoverflow.com/questions/20133320/saving-a-toisodate-gets-deserialized-as-a-non-iso-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!