我正在挖掘寻找解决方案,但没有找到它,我敢打赌有人遇到过这个问题,那么问题是什么?
为了测试,我创建了简单的控制台应用程序(解决方案将在 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 尚未更改。