ASP.NET Core appsettings.json update in code

后端 未结 9 1998
小鲜肉
小鲜肉 2020-12-13 01:54

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

\"AppSettings\": {
   \"AzureConnectionKey\": \"***\",
   \"Azu         


        
9条回答
  •  温柔的废话
    2020-12-13 02:27

    Update appsettings.json file in asp.net core runtime

    Sample appsettings.json file

    {
      Config: {
         IsConfig: false
      }
    }
    

    Code to update IsConfig property to true

    
    Main(){
    
     AddOrUpdateAppSetting("Config:IsConfig", true);
    
    }
    
    
    
    public static void AddOrUpdateAppSetting(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");
                }
            }
    
    

提交回复
热议问题