【发布时间】:2020-01-18 13:42:16
【问题描述】:
我一直在寻找解决方案,但没有找到,我打赌有人遇到过这个问题,那么问题是什么?
为了测试,我创建了简单的控制台应用程序(解决方案将用于 asp.net core web api)。
我已经设置了“始终复制”的 TestSetting.json 配置文件。
{
"setting1" : "value1"
}
简单的代码
IConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
IConfigurationRoot configuration = configurationBuilder.AddJsonFile("TestSettings.json",false, reloadOnChange: true).Build();
Console.WriteLine(configuration.GetSection("setting1").Value); // Output: value1
//Change configuration manually in file while console is waiting
Console.ReadKey();
//Changed manually in file Value appears
Console.WriteLine(configuration.GetSection("setting1").Value); // Output: Whatever you have setuped
Console.ReadKey();
configuration.GetSection("setting1").Value = "changed from code";
//Changed in code value appear
Console.WriteLine(configuration.GetSection("setting1").Value); // Output: changed from code
我有 2 个要求,我希望能够在应用程序运行时手动更改 json 配置文件中的值,并且应用程序将在下一次获取设置部分时看到更新的值并且它正在工作。
第二个要求是,我想保留一些信息,准确地说是任务的最后执行时间,应该在每个设置的周期前执行一次。每天一次,因此一些循环检查最后执行时间值并确定是否必须执行操作。有人会问我有什么可以工作,但我还需要涵盖执行操作和重新启动应用程序的场景(服务器错误、用户重新启动等),我需要以允许我的方式保存这些信息应用启动后阅读。
阅读代码示例,我们可以看到在更改代码中的设置 1 后,我们看到该部分在尝试将其输出到控制台时已更改。
configuration.GetSection("setting1").Value = "changed from code";
//Changed in code value appear
Console.WriteLine(configuration.GetSection("setting1").Value); // Output: changed from code
问题来了:)。此设置部分更改是否可能也会影响 json 文件中的实际值?我不想由某些流作家或其他人手动更改此文件。
实际结果是: 在代码中更改值后,新值可以在运行时获取,但是当您去调试二进制文件时,您会发现 TestSettings.json 文件中的 value1 没有更改。
【问题讨论】:
标签: c# asp.net-web-api .net-core