Javascript 多风';s WebApi控制器是否与UTC日期时间配合使用?

Javascript 多风';s WebApi控制器是否与UTC日期时间配合使用?,javascript,breeze,Javascript,Breeze,Breeze的JsonMediaTypeFormatter的设置有问题。 我要做的是WebAPI发送和接收json的日期 始终在UTC工作 根据,可以将JsonSerializerSettings的属性DateTimeZoneHandling设置为DateTimeZoneHandling.Utc 然而,这并没有起作用 经过调查,我意识到可能影响这一行为的是为其所做的黑客行为。 通过删除下面的所有代码,一切正常 //jsonSerializerSettings.Converters.Ad

Breeze的
JsonMediaTypeFormatter
的设置有问题。 我要做的是WebAPI发送和接收json的日期 始终在UTC工作

根据,可以将
JsonSerializerSettings的属性
DateTimeZoneHandling
设置为
DateTimeZoneHandling.Utc

然而,这并没有起作用

经过调查,我意识到可能影响这一行为的是为其所做的黑客行为。

通过删除下面的所有代码,一切正常

    //jsonSerializerSettings.Converters.Add(new IsoDateTimeConverter
    //{
    //    DateTimeFormat = "yyyy-MM-dd\\THH:mm:ss.fffK"
    //});
我如何处理这种情况而不必删除黑客

编辑1

我第一次尝试设置如下:

var jsonFormatter = Breeze.WebApi.JsonFormatter.Create();
jsonFormatter.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
jsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
jsonFormatter.SupportedEncodings.Add(new UTF8Encoding(false, true));
GlobalConfiguration.Configuration.Formatters.Insert(
          0, jsonFormatter);
但这不起作用,返回的日期不是UTC

编辑2

首先,我将Breeze库更新为0.80.3版本

在我的App_Start文件夹中,我有一个BreezeWebApiConfig.cs文件:

[assembly: WebActivator.PreApplicationStartMethod(
    typeof(Partner.App_Start.BreezeWebApiConfig), "RegisterBreezePreStart")]
namespace Partner.App_Start
{
    public static class BreezeWebApiConfig
    {
        public static void RegisterBreezePreStart()
        {
            GlobalConfiguration.Configuration.Routes.MapHttpRoute(
                name: "BreezeApi",
                routeTemplate: "api/{controller}/{action}"
            );

            var jsonFormatter = Breeze.WebApi.JsonFormatter.Create();
            jsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
            jsonFormatter.SupportedEncodings.Add(new UTF8Encoding(false, true));

            GlobalConfiguration.Configuration.Formatters.Insert(
                0, jsonFormatter);

            // Apply query parameters, expressed as OData URI query strings, 
            // to results of Web API controller methods that return IQueryable<T>
            GlobalConfiguration.Configuration.Filters.Add(
                new Breeze.WebApi.ODataActionFilter());
        }
    }
}
[程序集:WebActivator.PreApplicationStartMethod(
类型(Partner.App\u Start.BreezeWebApiConfig),“RegisterBreezePreStart”)]
namespace Partner.App_Start
{
公共静态类BreezeWebApiConfig
{
公共静态无效寄存器breezeprestart()
{
GlobalConfiguration.Configuration.Routes.MapHttpRoute(
名称:“BreezeApi”,
routeTemplate:“api/{controller}/{action}”
);
var jsonFormatter=Breeze.WebApi.jsonFormatter.Create();
jsonFormatter.SupportedMediaTypes.Add(新的MediaTypeHeaderValue(“应用程序/json”);
添加(新的UTF8Encoding(false,true));
GlobalConfiguration.Configuration.Formatters.Insert(
0,jsonFormatter);
//应用查询参数,以ODataURI查询字符串表示,
//返回IQueryable的Web API控制器方法的结果
GlobalConfiguration.Configuration.Filters.Add(
newbreeze.WebApi.ODataActionFilter());
}
}
}
其次,我在一个名为BreezeConfig的文件夹中创建了一个CustomBreezeConfig.cs类(使用Jay在下面描述的代码),但这个新尝试没有成功

问候,


Bernardo Pacheco

当你说添加DateTimeZone处理不起作用时,你是如何设置的

您可以尝试在源代码中的“Converters.Add”调用(从上面)的正上方添加这一行(不删除“hack”),然后告诉我它是否有效

 jsonSerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;

我同意这仍然很笨拙,因为这意味着必须修改微风源。因此,如果它确实有效,我们将尝试想出一些方法,允许您从格式化程序外部设置它。请告诉我们。

当您说添加DateTimeZone处理不起作用时,您是如何尝试设置的

您可以尝试在源代码中的“Converters.Add”调用(从上面)的正上方添加这一行(不删除“hack”),然后告诉我它是否有效

 jsonSerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;

我同意这仍然很笨拙,因为这意味着必须修改微风源。因此,如果它确实有效,我们将尝试想出一些方法,允许您从格式化程序外部设置它。请让我们知道。

我用这个黑客解决了utc的问题,它仍然很臭

在app.vm.run.js中

app.vm.run = (function ($, ko, dataservice, router) {
var currentRunId = ko.observable(),
    // run will be an entity
    run = ko.observable(),
...
   save = function () {
        this.run().lastUpdate(makeDatetimeUTC(moment().toDate()));
        this.run().runStart(makeDatetimeUTC(this.run().runStart()));
        this.run().runEnd(makeDatetimeUTC(this.run().runEnd()));
        dataservice.saveChanges();
        // the test r === run() succeeds because the local run is a 
        //  ko.observable which is bound to the run in the cache
        var r = dataservice.getRunById(currentRunId());
    },
...

})($, ko, app.dataservice, app.router);
在myScripts.js中

// Here is a real pain in the neck.
//  For some reason, when the entity is saved, it shows up on the server as UTC datetime
//  instead of local.  Moment parses everything as local by default, so the formatDate function
//  used to get a display value needs to be converted to utc before it is returned to the server.
// 
// This function takes the value of the dependentObservable in the entity
//  and converts it to a string which can be stored back into the entity before sending
//  it to the server.
//
// The reason I need to do that is so that it displays properly after the save.      
//  The date seems to be handled properly by the server.

var makeDatetimeUTC = function(localDatetime) {
    var datestring = formatDate(localDatetime);
    var utc = moment.utc(datestring);
    return formatDate(utc);
};

var formatDate = function(dateToFormat) {
    if (dateToFormat === null ||dateToFormat === undefined || dateToFormat.length === 0)
        return "";

    // intermediate variable is not needed, but is good for debugging
    var formattedDate = moment(dateToFormat).format('MM/DD/YYYY hh:mm A');
    return formattedDate;
    },
    formatObservableDate = function(observable) {
        if (ko.isObservable(observable))
            return observable(formatDate(observable()));
        else
            throw new Error("formatObservableDate expected a ko.Observable ");
    };

我用这个黑客解决了utc的问题,它仍然很臭

在app.vm.run.js中

app.vm.run = (function ($, ko, dataservice, router) {
var currentRunId = ko.observable(),
    // run will be an entity
    run = ko.observable(),
...
   save = function () {
        this.run().lastUpdate(makeDatetimeUTC(moment().toDate()));
        this.run().runStart(makeDatetimeUTC(this.run().runStart()));
        this.run().runEnd(makeDatetimeUTC(this.run().runEnd()));
        dataservice.saveChanges();
        // the test r === run() succeeds because the local run is a 
        //  ko.observable which is bound to the run in the cache
        var r = dataservice.getRunById(currentRunId());
    },
...

})($, ko, app.dataservice, app.router);
在myScripts.js中

// Here is a real pain in the neck.
//  For some reason, when the entity is saved, it shows up on the server as UTC datetime
//  instead of local.  Moment parses everything as local by default, so the formatDate function
//  used to get a display value needs to be converted to utc before it is returned to the server.
// 
// This function takes the value of the dependentObservable in the entity
//  and converts it to a string which can be stored back into the entity before sending
//  it to the server.
//
// The reason I need to do that is so that it displays properly after the save.      
//  The date seems to be handled properly by the server.

var makeDatetimeUTC = function(localDatetime) {
    var datestring = formatDate(localDatetime);
    var utc = moment.utc(datestring);
    return formatDate(utc);
};

var formatDate = function(dateToFormat) {
    if (dateToFormat === null ||dateToFormat === undefined || dateToFormat.length === 0)
        return "";

    // intermediate variable is not needed, but is good for debugging
    var formattedDate = moment(dateToFormat).format('MM/DD/YYYY hh:mm A');
    return formattedDate;
    },
    formatObservableDate = function(observable) {
        if (ko.isObservable(observable))
            return observable(formatDate(observable()));
        else
            throw new Error("formatObservableDate expected a ko.Observable ");
    };

从BreezeV0.80.3开始,我们已经添加了定制json序列化程序设置的功能,breeze将这些设置用于查询和保存。它包括添加一个服务器端类,该类是新的Breeze.WebApi.BreezeConfig类的子类。此子类将类似于:

 public class CustomBreezeConfig : Breeze.WebApi.BreezeConfig {

    /// <summary>
    /// Overriden to create a specialized JsonSerializer implementation that uses UTC date time zone handling.
    /// </summary>
    protected override JsonSerializerSettings CreateJsonSerializerSettings() {
      var baseSettings = base.CreateJsonSerializerSettings();
      baseSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
      return baseSettings;
    }
  }
public类CustomBreezeConfig:Breeze.WebApi.BreezeConfig{
/// 
///重写以创建使用UTC日期时区处理的专用JsonSerializer实现。
/// 
受保护的重写JsonSerializerSettings CreateJsonSerializerSettings(){
var baseSettings=base.CreateJsonSerializerSettings();
baseSettings.DateTimeZoneHandling=DateTimeZoneHandling.Utc;
返回基本设置;
}
}
服务器端项目中出现的Breeze.WebApi.BreezeConfig子类的任何实例现在都将被自动发现并用于自定义Breeze的配置


请告诉我们这是否有帮助。

从breeze v 0.80.3开始,我们已经添加了自定义breeze用于查询和保存的json序列化程序设置的功能。它包括添加一个服务器端类,该类是新的Breeze.WebApi.BreezeConfig类的子类。此子类将类似于:

 public class CustomBreezeConfig : Breeze.WebApi.BreezeConfig {

    /// <summary>
    /// Overriden to create a specialized JsonSerializer implementation that uses UTC date time zone handling.
    /// </summary>
    protected override JsonSerializerSettings CreateJsonSerializerSettings() {
      var baseSettings = base.CreateJsonSerializerSettings();
      baseSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
      return baseSettings;
    }
  }
public类CustomBreezeConfig:Breeze.WebApi.BreezeConfig{
/// 
///重写以创建使用UTC日期时区处理的专用JsonSerializer实现。
/// 
受保护的重写JsonSerializerSettings CreateJsonSerializerSettings(){
var baseSettings=base.CreateJsonSerializerSettings();
baseSettings.DateTimeZoneHandling=DateTimeZoneHandling.Utc;
返回基本设置;
}
}
服务器端项目中出现的Breeze.WebApi.BreezeConfig子类的任何实例现在都将被自动发现并用于自定义Breeze的配置


请告诉我们这是否有用。

请尝试breeze v 0.80.5以及相应的发行说明。希望“时间”现在可以正常往返

请尝试breeze v 0.80.5以及相应的发行说明。希望“时间”现在可以正常往返

GitHub中最新的[BreezeController]属性应该更容易将格式化程序交付给控制器。该属性将很快发布并出现在NuGet包中。这种改进并不能让你更容易理解