我有。net core 5.0应用程序,并尝试从appsettings.json中获取DateTime
appsettings.json:
"TimeModel": {
"RestartDuration": "27.10.2021 12:30:00"
}
代码:
services.Configure<TimeModel>(
configuration.GetSection("TimeModel"));
错误:
System.InvalidOperationException: Failed to convert configuration value at 'TimeModel:RestartDuration' to type 'System.DateTime'.
---> System.FormatException: 27.10.2021 12:30:00 is not a valid value for DateTime.
---> System.FormatException: String '27.10.2021 12:30:00' was not recognized as a valid DateTime.
有几种方法可以做到:
- 获取日期作为字符串,然后解析:
DateTime.Parse(configuration.GetValue<string>("Date"))
- 可直接获取:
configuration.GetValue<DateTime>("TimeModel")
您可以使用类模型。
在所有情况下,您需要确保日期的格式默认为:2021-10-27T12:30:00
。