小编Paw*_*zak的帖子

将 IConfigurationRoot 部分的更改保存到 .net Core 2.2 中的 *.json 文件

我一直在寻找解决方案,但没有设法找到它,我敢打赌有人遇到过这个问题,那么问题是什么?。

为了测试,我创建了简单的控制台应用程序(解决方案将在 asp.net core web api 中使用)。

我已经设置了“始终复制”的 TestSetting.json 配置文件。

{
  "setting1" : "value1" 
}
Run Code Online (Sandbox Code Playgroud)

和简单的代码

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
Run Code Online (Sandbox Code Playgroud)

我有 2 个要求,我希望可以在应用程序运行时手动更改 json 配置文件中的值,并且应用程序将在下次获取设置部分时看到更新的值并且它正在工作。

第二个要求是,我想保留一些信息,准确地说是任务的最后执行时间,应该在每个设置的时间段执行一次,例如。每天一次,所以一些循环检查上次执行时间值并确定是否必须执行操作。有人会问我有什么可以工作,但我还需要涵盖执行操作和重新启动应用程序时的场景(服务器错误、用户重新启动等),我需要以一种允许我的方式保存这些信息在应用程序启动后阅读它。

阅读代码示例我们可以看到,在代码中更改 setting1 后,我们看到该部分在尝试将其输出到控制台时已更改。 …

c# asp.net-web-api .net-core

2
推荐指数
2
解决办法
4419
查看次数

标签 统计

.net-core ×1

asp.net-web-api ×1

c# ×1