问题
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.
回答1:
Here is a relevant article from Microsoft regarding Configuration setup in .Net Core Apps:
Asp.Net Core Configuration
The page also has sample code which may also be helpful.
Update
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
is only supported in ASP.NET Core 1.1 and higher.
回答2:
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.
回答3:
Update appsettings.json file in asp.net core runtime
Sample appsettings.json file
{
Config: {
IsConfig: false
}
}
Code to update IsConfig property to true
Main(){
AddUpdateAppSettings("Config:IsConfig", true);
}
public static void AddUpdateAppSettings<T>(string key, T value) {
try {
var filePath = Path.Combine(AppContext.BaseDirectory, "appSettings.json");
string json = File.ReadAllText(filePath);
dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
var sectionPath = key.Split(":")[0];
if (!string.IsNullOrEmpty(sectionPath)) {
var keyPath = key.Split(":")[1];
jsonObj[sectionPath][keyPath] = value;
}
else {
jsonObj[sectionPath] = value; // if no sectionpath just set the value
}
string output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);
File.WriteAllText(filePath, output);
}
catch (ConfigurationErrorsException) {
Console.WriteLine("Error writing app settings");
}
}
回答4:
Suppose appsettings.json has an eureka port, and want to change it dynamically in args (-p 5090). By doing this, can make change to the port easily for docker when creating many services.
"eureka": {
"client": {
"serviceUrl": "http://10.0.0.101:8761/eureka/",
"shouldRegisterWithEureka": true,
"shouldFetchRegistry": false
},
"instance": {
"port": 5000
}
}
public class Startup
{
public static string port = "5000";
public Startup(IConfiguration configuration)
{
configuration["eureka:instance:port"] = port;
Configuration = configuration;
}
public static void Main(string[] args)
{
int port = 5000;
if (args.Length>1)
{
if (int.TryParse(args[1], out port))
{
Startup.port = port.ToString();
}
}
}
来源:https://stackoverflow.com/questions/41653688/asp-net-core-appsettings-json-update-in-code