ASP.NET Core appsettings.json在代码中更新

我目前正在使用asp.net core v1.1开发项目,在我的appsettings.json中我有:

"AppSettings": { "AzureConnectionKey": "***", "AzureContainerName": "**", "NumberOfTicks": 621355968000000000, "NumberOfMiliseconds": 10000, "SelectedPvInstalationIds": [ 13, 137, 126, 121, 68, 29 ], "MaxPvPower": 160, "MaxWindPower": 5745.35 }, 

我也有用来存储它们的类:

 public class AppSettings { public string AzureConnectionKey { get; set; } public string AzureContainerName { get; set; } public long NumberOfTicks { get; set; } public long NumberOfMiliseconds { get; set; } public int[] SelectedPvInstalationIds { get; set; } public decimal MaxPvPower { get; set; } public decimal MaxWindPower { get; set; } } 

然后启用DI在Startup.cs中使用:

 services.Configure(Configuration.GetSection("AppSettings")); 

有没有办法从Controller更改和保存MaxPvPowerMaxWindPower

我试过用

 private readonly AppSettings _settings; public HomeController(IOptions settings) { _settings = settings.Value; } [Authorize(Policy = "AdminPolicy")] public IActionResult UpdateSettings(decimal pv, decimal wind) { _settings.MaxPvPower = pv; _settings.MaxWindPower = wind; return Redirect("Settings"); } 

但它没有做任何事情。

以下是Microsoft关于.Net Core Apps中的配置设置的相关文章:

Asp.Net核心配置

该页面还有示例代码 ,也可能有所帮助。

更新

我认为内存提供程序和绑定到POCO类可能有一些用处,但不能像预期的那样工作。

下一个选项可以是在添加配置文件并手动解析JSON配置文件并按预期进行更改时将reloadOnChange参数设置为true。

  public class Startup { ... public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } ... } 

…仅在ASP.NET Core 1.1及更高版本中支持reloadOnChange

基本上你可以在IConfiguration设置这样的值:

 IConfiguration configuration = ... // ... configuration["key"] = "value"; 

问题在于例如JsonConfigurationProvider没有实现将配置保存到文件中。 正如您在源代码中看到的那样,它不会覆盖ConfigurationProvider的Set方法。 (见来源 )

您可以创建自己的提供商并在那里实施保存。 这里(entity framework自定义提供程序的基本示例)是一个如何执行此操作的示例。