ASP.NET Core appsettings.json update in code

纵饮孤独 提交于 2019-11-29 22:30:24
Ankit

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.

Mathias

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.

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();
            }

        }
     }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!