简体   繁体   English

.NET自定义配置:使用文化区域不变/ XML格式序列化DateTimeOffest属性?

[英].NET custom configuration: serializing DateTimeOffest properties using a culture-invariant / XML format?

I'm using a custom configuration section within an MVC web application I'm currently working on. 我正在当前正在使用的MVC Web应用程序中使用自定义配置部分。 Given the following property MyProperty of type System.DateTimeOffset within a custom ConfigurationElement implementation: 在自定义ConfigurationElement实现中,给定System.DateTimeOffset类型的以下属性MyProperty

public class MyClass : ConfigurationElement
{
    /// other properties...

    [ConfigurationProperty("myDateProperty", IsRequired = true)]
    public DateTimeOffset MyDateProperty
    {
        get
        {
            return (DateTimeOffset)this["myDateProperty"];
        }

        set
        {
            this["myDateProperty"] = value;
        }
    }
}

Could anyone explain why this gets serialized within the config file using (presumably) the en-US culture, like so: 谁能解释为什么它使用(大概) en-US文化在配置文件中序列化,如下所示:

    <add key="..." myDateProperty="10/02/2017 12:19:38 +01:00" />

I would have hoped the value would have be serialized in a culture-invariant format or XML format, eg: 我希望该值可以以文化不变的格式或XML格式进行序列化,例如:

    <add key="..." myDateProperty="2017-10-02T12:19:38+01:00" />

How can I specify a culture-invariant / XML format for serializing date-related properties? 如何为序列化与日期相关的属性指定文化不变性/ XML格式?

Additional details which may or may not be important: 可能不重要的其他详细信息:

  • I'm writing the values to a separate config file (referenced within web.config ); 我将这些值写入一个单独的配置文件(在web.config引用);
  • The target .NET Framework is v4; 目标.NET Framework是v4;
  • The application's Thread.CurrentCulture and Thread.CurrentUICulture are both set (implicitly) to en-GB ; 应用程序的Thread.CurrentCultureThread.CurrentUICulture都(隐式)设置为en-GB
  • The same issue also occurs if I change the type to System.DateTime . 如果将类型更改为System.DateTime也会发生相同的问题。

For me works fine: 对我来说效果很好:

Thread.CurrentThread.CurrentCulture = new MyCultureInfo(CultureInfo.InvariantCulture.Name);

MyDateTimeFormat: MyDateTimeFormat:

public class MyCultureInfo : CultureInfo
{
    ......implement constructors       

    private DateTimeFormatInfo dateTimeFormatInfo;
    public override DateTimeFormatInfo DateTimeFormat {
        get
        {
            if (dateTimeFormatInfo == null)
            {
                var dateTimeFormatInfo = new DateTimeFormatInfo();
                dateTimeFormatInfo.FullDateTimePattern = "yyyy-MM-ddTHH:mm:ssK";
                dateTimeFormatInfo.LongTimePattern = "yyyy-MM-ddTHH:mm:ssK";
            }
            return dateTimeFormatInfo;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM