What is the equivalent of Web.config transform in ASP.NET Core?

后端 未结 2 1141
刺人心
刺人心 2021-01-12 10:43

ASP.NET Core documentation suggests we should use appsettings.json file, along with a file per environment, containing overriding values. The problem is that all these files

2条回答
  •  孤街浪徒
    2021-01-12 11:27

    We can start by looking at the predefined ConfigurationBuilder that usually looks something like this:

    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
        .AddEnvironmentVariables();
    
    Configuration = builder.Build();
    

    You can opt to remove the AddJosnFile() if you don't want them in the first place, as sometimes your project may not require this.

    If you do intend to use the appsettings.json or similar, then it is important to note the order they are added. You can see in the code snippet above, that the appsettings.{env}.json is added after.

    This is an important concept to understand, because this means that if there is a file found that matches the filename (for example, appsettings.Production.json), it will replace.override any overlapping configurations.

    Note the use of the words replace, override and overlapping.

    You can architect your own tiers and layer your configurations in a suitable way to fit your project. You are not restrained to have on use the env.EnviornmentName either, you can use any kind of conditional logic to design it as needed.

    If you plan to go this route of customized design. You may want to note that you can reconfigure and alter the configuration as much as you like prior to the WebHostBuilder being built (i.e. before the .Build() method is called). So, you can be very creative in how you want to programmatically configure your project.

提交回复
热议问题