代码中的ASP.NET Core appsettings.json更新 [英] ASP.NET Core appsettings.json update in code

查看:783
本文介绍了代码中的ASP.NET Core appsettings.json更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am currently working on project using asp.net core v1.1, and in my appsettings.json I have:

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

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

I also have class that I use to store them:

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以供使用:

And DI enabled to use then in Startup.cs:

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

是否可以通过Controller更改和保存MaxPvPowerMaxWindPower?

Is there any way to change and save MaxPvPower and MaxWindPower from Controller?

我尝试使用

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");
 }

但是它什么也没做.

推荐答案

此处是Microsoft的有关.Net Core Apps中的配置设置的相关文章:

Here is a relevant article from Microsoft regarding Configuration setup in .Net Core Apps:

Asp.Net核心配置

该页面还具有示例代码可能也有帮助.

The page also has sample code which may also be helpful.

更新

我认为内存提供程序并绑定到POCO类可能有用,但不能按OP预期的那样工作.

I thought In-memory provider and binding to a POCO class might be of some use but does not work as OP expected.

下一个选项可以设置

The next option can be setting reloadOnChange parameter of AddJsonFile to true while adding the configuration file and manually parsing the JSON configuration file and making changes as intended.

    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();
        }
        ...
    }

... reloadOnChange仅在ASP.NET Core 1.1和更高版本中受支持.

... reloadOnChange is only supported in ASP.NET Core 1.1 and higher.

这篇关于代码中的ASP.NET Core appsettings.json更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆