gpt4 book ai didi

c# - 代码中的 ASP.NET Core appsettings.json 更新

转载 作者:可可西里 更新时间:2023-11-01 03:09:02 27 4
gpt4 key购买 nike

我目前正在使用 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; }
}

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

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

有什么方法可以从 Controller 更改和保存 MaxPvPowerMaxWindPower 吗?

我试过用

private readonly AppSettings _settings;

public HomeController(IOptions<AppSettings> settings)
{
_settings = settings.Value;
}

[Authorize(Policy = "AdminPolicy")]
public IActionResult UpdateSettings(decimal pv, decimal wind)
{
_settings.MaxPvPower = pv;
_settings.MaxWindPower = wind;

return Redirect("Settings");
}

但它什么也没做。

最佳答案

基本上,您可以像这样在 IConfiguration 中设置值:

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

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

您可以创建自己的提供程序并在那里实现保存。 Here (Basic sample of Entity Framework custom provider)是一个如何做到这一点的例子。

关于c# - 代码中的 ASP.NET Core appsettings.json 更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41653688/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com