如何在ASP.NET Core 2.1中全局格式化NodaTime日期字符串?

问题描述 投票:4回答:1

目前,我正在尝试使用JsonFormatters序列化ISO 8601规范中的字符串。在我的启动配置中格式化,但无法使其工作。

我的启动配置如下:

services.AddMvcCore(
    (options) => {
        options.SslPort = 44321;
        options.Filters.Add(new RequireHttpsAttribute());
    }
)
.AddJsonFormatters(jsonSerializerSettings => {
    jsonSerializerSettings.DateParseHandling = DateParseHandling.None;
    jsonSerializerSettings.DateFormatString = "yyyy-MM-ddTHH:mm:ss.fffZ";
})
.AddApiExplorer()
.AddJsonOptions(options => {
    options.AllowInputFormatterExceptionMessages = false;
    options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
})
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
.AddDataAnnotationsLocalization();

我也尝试过在ServiceStackText中提到的documentation,但这也没有用。

 NodaSerializerDefinitions.LocalTimeSerializer.ConfigureSerializer();
 DateTimeZoneProviders.Tzdb
     .CreateDefaultSerializersForNodaTime()
     .ConfigureSerializersForNodaTime();

我一直得到以下格式,

即对于LocalDate序列化:

{
    "patientDob": "Thursday, June 15, 2017",
}

如何配置字符串ISO 8601规范。全局格式化NodaTime日期类型?

我的模特,

{
    public LocalDate patientDob { get; set; }
}

和我的视图模型/ API资源:

{
    public string patientDob { get; set; }
}
nodatime asp.net-core-2.1 json-serialization
1个回答
17
投票

这是您控制器中的问题:

res.NodaLocalDateString = apiResource.NodaLocalDate = nodaModel.NodaLocalDate.ToString ();

你根本没有将LocalDate转换成JSON;您正在将字符串转换为JSON,并且您通过调用LocalDate.ToString()获取该字符串。

将您的API资源更改为具有LocalDate属性而不是string属性,以便转换由Json.NET而不是您调用ToString()完成。

© www.soinside.com 2019 - 2024. All rights reserved.