C# ASP.NET核心appsettings.json更新代码
我目前正在使用asp.net core v1.1开发项目,在我的appsettings.json中,我有:C# ASP.NET核心appsettings.json更新代码,c#,json,asp.net-core,.net-core,appsettings,C#,Json,Asp.net Core,.net Core,Appsettings,我目前正在使用asp.net core v1.1开发项目,在我的appsettings.json中,我有: "AppSettings": { "AzureConnectionKey": "***", "AzureContainerName": "**", "NumberOfTicks": 621355968000000000, "NumberOfMiliseconds": 10000, "SelectedPvInstalationIds": [ 13, 137, 1
"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"));
但它什么也没做。以下是微软关于.Net核心应用程序配置设置的相关文章: 该页面还提供了一些可能会有所帮助的信息 更新 我认为可能有一些用处,但并不像OP预期的那样有效 下一个选项是在添加配置文件和 手动解析JSON配置文件并按预期进行更改
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及更高版本中受支持
基本上,您可以在
i配置中设置如下值:
IConfiguration configuration = ...
// ...
configuration["key"] = "value";
存在的问题是,JsonConfigurationProvider
没有实现将配置保存到文件中。正如您在中所看到的,它不会覆盖ConfigurationProvider
的Set方法。(见附件)
您可以创建自己的提供者并在那里实现保存。下面是一个示例。假设appsettings.json有一个eureka端口,并希望在args(-p 5090)中动态更改它。通过这样做,docker可以在创建许多服务时轻松地更改端口
"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();
}
}
}
在asp.net核心运行时中更新appsettings.json文件
示例appsettings.json文件
将IsConfig属性更新为true的代码
Main(){
AddOrUpdateAppSetting(“配置:IsConfig”,true);
}
公共静态void AddOrUpdateAppSetting(字符串键,T值){
试试{
var filePath=Path.Combine(AppContext.BaseDirectory,“appSettings.json”);
字符串json=File.ReadAllText(文件路径);
动态jsonObj=Newtonsoft.Json.JsonConvert.DeserializeObject(Json);
var sectionPath=key.Split(“:”[0];
如果(!string.IsNullOrEmpty(sectionPath)){
var keyPath=key.Split(“:”[1];
jsonObj[sectionPath][keyPath]=值;
}
否则{
jsonObj[sectionPath]=value;//如果没有sectionPath,请设置该值
}
字符串输出=Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj,Newtonsoft.Json.Formatting.Indented);
writealText(文件路径,输出);
}
捕获(配置错误异常){
Console.WriteLine(“写入应用程序设置时出错”);
}
}
公共静态无效设置AppSettingValue(字符串键、字符串值、字符串appSettingsJsonFilePath=null)
{
if(appSettingsJsonFilePath==null)
{
appsetingsjsonfilepath=System.IO.Path.Combine(System.AppContext.BaseDirectory,“appsettings.json”);
}
var json=System.IO.File.ReadAllText(appSettingsJsonFilePath);
动态jsonObj=Newtonsoft.Json.JsonConvert.DeserializeObject(Json);
jsonObj[key]=值;
字符串输出=Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj,Newtonsoft.Json.Formatting.Indented);
System.IO.File.writealText(appsetingsjsonfilepath,输出);
}
我正在使用我自己的配置部分和我自己的强类型对象。我总是用这个强类型对象注入IOptions。我可以在运行时更改配置。对对象的作用域要非常小心。新的配置值由请求作用域对象拾取。我正在使用构造函数注入
但是,关于这方面的文件还不清楚。。我不确定这是否是命中注定的。阅读此我获取了Qamar Zamans代码(谢谢),并对其进行了修改,以允许编辑超过一层的参数
希望它能帮助一些人,惊讶的是,这不是一个图书馆功能的地方
public static class SettingsHelpers
{
public static void AddOrUpdateAppSetting<T>(string sectionPathKey, T value)
{
try
{
var filePath = Path.Combine(AppContext.BaseDirectory, "appsettings.json");
string json = File.ReadAllText(filePath);
dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
SetValueRecursively(sectionPathKey, jsonObj, value);
string output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);
File.WriteAllText(filePath, output);
}
catch (Exception ex)
{
Console.WriteLine("Error writing app settings | {0}", ex.Message);
}
}
private static void SetValueRecursively<T>(string sectionPathKey, dynamic jsonObj, T value)
{
// split the string at the first ':' character
var remainingSections = sectionPathKey.Split(":", 2);
var currentSection = remainingSections[0];
if (remainingSections.Length > 1)
{
// continue with the procress, moving down the tree
var nextSection = remainingSections[1];
SetValueRecursively(nextSection, jsonObj[currentSection], value);
}
else
{
// we've got to the end of the tree, set the value
jsonObj[currentSection] = value;
}
}
公共静态类设置搁置器
{
公共静态void AddOrUpdateAppSetting(字符串部分路径键,T值)
{
尝试
{
var filePath=Path.Combine(AppContext.BaseDirectory,“appsettings.json”);
字符串json=File.ReadAllText(文件路径);
动态jsonObj=Newtonsoft.Json.JsonConvert.DeserializeObject(Json);
递归地设置值(sectionPathKey,jsonObj,value);
字符串输出=Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj,Newtonsoft.Json.Formatting.Indented);
writealText(文件路径,输出);
}
捕获(例外情况除外)
{
WriteLine(“写入应用程序设置{0}时出错”,例如Message);
}
}
私有静态void setvalue递归(字符串部分路径键、动态jsonObj、T值)
{
//在第一个“:”字符处拆分字符串
var remainingSections=sectionPathKey.Split(“:”,2);
var currentSection=剩余部分[0];
如果(剩余节长>1)
{
//继续生产,沿着树向下移动
var nextSection=剩余部分[1];
递归设置值(下一节,jsonObj[currentSection],值);
}
其他的
{
//我们已经到了树的末尾,设置值
jsonObj[currentSection]=值;
}
}
有一个esier答案可以在运行时修改appsettings.json
var filePath=Path.Combine(System.AppContext.BaseDirectory,“appSettings.json”);
字符串jsonString=System.IO.File.ReadAllText(文件路径);
//使用https://json2csharp.com/ 从json创建c#类
Root=JsonSerializer.Deserialize(jsonString);
var dbtoadd=新数据库()
{
Id=“myid”,
Name=“mynewdb”,
ConnectionString=“”
};
//向此对象添加或更改任何内容,就像您在任何列表中所做的一样
root.DatabaseSettings.Databases.Add(dbtoadd);
//意甲
{
Config: {
IsConfig: false
}
}
public static class SettingsHelpers
{
public static void AddOrUpdateAppSetting<T>(string sectionPathKey, T value)
{
try
{
var filePath = Path.Combine(AppContext.BaseDirectory, "appsettings.json");
string json = File.ReadAllText(filePath);
dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
SetValueRecursively(sectionPathKey, jsonObj, value);
string output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);
File.WriteAllText(filePath, output);
}
catch (Exception ex)
{
Console.WriteLine("Error writing app settings | {0}", ex.Message);
}
}
private static void SetValueRecursively<T>(string sectionPathKey, dynamic jsonObj, T value)
{
// split the string at the first ':' character
var remainingSections = sectionPathKey.Split(":", 2);
var currentSection = remainingSections[0];
if (remainingSections.Length > 1)
{
// continue with the procress, moving down the tree
var nextSection = remainingSections[1];
SetValueRecursively(nextSection, jsonObj[currentSection], value);
}
else
{
// we've got to the end of the tree, set the value
jsonObj[currentSection] = value;
}
}
var filePath = Path.Combine(System.AppContext.BaseDirectory, "appSettings.json");
string jsonString = System.IO.File.ReadAllText(filePath);
//use https://json2csharp.com/ to create the c# classes from your json
Root root = JsonSerializer.Deserialize<Root>(jsonString);
var dbtoadd = new Databas()
{
Id = "myid",
Name = "mynewdb",
ConnectionString = ""
};
//add or change anything to this object like you do on any list
root.DatabaseSettings.Databases.Add(dbtoadd);
//serialize the new updated object to a string
string towrite = JsonSerializer.Serialize(root);
//overwrite the file and it wil contain the new data
System.IO.File.WriteAllText(filePath, towrite);
public static class SettingsHelpers
{
public static void AddOrUpdateAppSetting<T>(T value, IWebHostEnvironment webHostEnvironment)
{
try
{
var settingFiles = new List<string> { "appsettings.json", $"appsettings.{webHostEnvironment.EnvironmentName}.json" };
foreach (var item in settingFiles)
{
var filePath = Path.Combine(AppContext.BaseDirectory, item);
string json = File.ReadAllText(filePath);
dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
SetValueRecursively(jsonObj, value);
string output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);
File.WriteAllText(filePath, output);
}
}
catch (Exception ex)
{
throw new Exception($"Error writing app settings | {ex.Message}", ex);
}
}
private static void SetValueRecursively<T>(dynamic jsonObj, T value)
{
var properties = value.GetType().GetProperties();
foreach (var property in properties)
{
var currentValue = property.GetValue(value);
if (property.PropertyType.IsPrimitive || property.PropertyType == typeof(string) || property.PropertyType == typeof(decimal))
{
if (currentValue == null) continue;
try
{
jsonObj[property.Name].Value = currentValue;
}
catch (RuntimeBinderException)
{
jsonObj[property.Name] = new JValue(currentValue);
}
continue;
}
try
{
if (jsonObj[property.Name] == null)
{
jsonObj[property.Name] = new JObject();
}
}
catch (RuntimeBinderException)
{
jsonObj[property.Name] = new JObject(new JProperty(property.Name));
}
SetValueRecursively(jsonObj[property.Name], currentValue);
}
}
}
public void UpdateAppSetting(string key, string value)
{
var configJson = File.ReadAllText("appsettings.json");
var config = JsonSerializer.Deserialize<Dictionary<string, object>>(configJson);
config[key] = value;
var updatedConfigJson = JsonSerializer.Serialize(config, new JsonSerializerOptions { WriteIndented = true });
File.WriteAllText("appsettings.json", updatedConfigJson);
}