ASP.NET Core appsettings.json update in code

后端 未结 9 1987
小鲜肉
小鲜肉 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:37

    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.

    0 讨论(0)
  • 2020-12-13 02:42

    According to Qamar Zaman and Alex Horlock codes, I've changed it a little bit.

     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);
            }
    
    
        }
    }
    
    0 讨论(0)
  • 2020-12-13 02:45
        public static void SetAppSettingValue(string key, string value, string appSettingsJsonFilePath = null)
        {
            if (appSettingsJsonFilePath == null)
            {
                appSettingsJsonFilePath = System.IO.Path.Combine(System.AppContext.BaseDirectory, "appsettings.json");
            }
    
            var json =   System.IO.File.ReadAllText(appSettingsJsonFilePath);
            dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject<Newtonsoft.Json.Linq.JObject>(json);
    
            jsonObj[key] = value;
    
            string output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);
    
            System.IO.File.WriteAllText(appSettingsJsonFilePath, output);
        }
    
    0 讨论(0)
提交回复
热议问题