ASP.NET Core appsettings.json update in code

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

    I took Qamar Zamans code (thank you) and modified it to allow for editing parameters which are more:than:one:layer:deep.

    Hope it helps someone out, surprised that this isn't a library feature somewhere.

    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; 
            }
        }
    
    0 讨论(0)
  • 2020-12-13 02:22

    There is an esier answer to modify the appsettings.json at runtime.

    Json File structure

    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);
    
    0 讨论(0)
  • 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<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");
                }
            }
    
    
    0 讨论(0)
  • 2020-12-13 02:34

    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();
                }
    
            }
         }
    
    0 讨论(0)
  • 2020-12-13 02:34

    I'm using my own configuration section and my own strongly typed object. I'm always injecting IOptions with this strongly typed object. And I'm able to change configuration in runtime. Be very careful with scopes of objects. New configuration values are picked up by request scoped object. I'm using constructor injection.

    Documentation on this is very unclear though .. I'm no sure if this is meant to be. Read this in-depth discussion

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

    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.

    0 讨论(0)
提交回复
热议问题