ASP.NET Core appsettings.json update in code

Siemko picture Siemko · Jan 14, 2017 · Viewed 57.3k times · Source

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

And DI enabled to use then in Startup.cs:

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

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

I tried using

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

But it did nothing.

Answer

Mathias picture Mathias · Jul 26, 2017

Basically you can set the values in IConfiguration like this:

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

The issue there is that e.g. the JsonConfigurationProvider does not implement the saving of the configuration into the file. As you can see in the source it does not override the Set method of ConfigurationProvider. (see source)

You can create your own provider and implement the saving there. Here (Basic sample of Entity Framework custom provider) is an example how to do it.