I'm currently making the switch from .NET Framework to .NET Core. In the past, all of my application settings were in the Web.config file. When I added a new publish profile, I could right click and select 'Add Config Transform' which would generate a nested Web.{Profile}.config file under Web.config where I could set application settings that were specific to the respective profile.
Now, in .NET Core, I want to achieve the same effect using an appsettings.json file instead of Web.config file. How can I create an appsettings.{Profile}.json file which will be nested under my appsettings.json file and contain settings that are specific to my publish profile? Of course, I can create the file manually, but what is it that 'links' the settings so that they will override appsettings.json when the application is published? Is there a simple way to do this in Visual Studio like I described for my old .NET Framework projects? Or am I missing something?
Thanks!
but what is it that 'links' the settings so that they will override appsettings.json when the application is published?
The appsettings are configured by WebHost
in Program.cs
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
In the implementation of webhost.cs the framework adds the appsettings to the webhost:
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
The second line is where it adds the environment specific appsettings
. Within Visual Studio this environment variable is defined in the Project Settings -> Debug
page and is called ASPNETCORE_ENVIRONMENT
. By default it is set to Development
so when you build and run within Visual Studio the appsettings.development.json
file (if it exists) will be loaded and override any matching settings in the appsettings.json
file.
When you publish your application you can override this value using an OS environment variable of the same name. There is an hierarchy of where .NET Core reads the values from and has a "last one wins " policy.
The hierarchy is currently:
- Files (appsettings.json, appsettings.{Environment}.json, where {Environment} is the app's current hosting environment)
- Azure Key Vault
- User secrets (Secret Manager) (in the Development environment only)
- Environment variables
- Command-line arguments
So when you publish your app you can override the environment on the host OS using an environment variable. When .NET Core starts your published app it will read that variables and load the appropriate appsettings.{environment}.json file. IF the value is not set, or no file exists for that environment, then the settings in appsettings.json
will apply.
You can read more about the ASPNETCORE_ENVIROMENT
setting here