I've defined some values in my appsettings.json
for things like database connection strings, webapi locations and the like which are different for development, staging and live environments.
Is there a way to have multiple appsettings.json
files (like appsettings.live.json
, etc, etc) and have the asp.net app just 'know' which one to use based on the build configuration it's running?
You can make use of environment variables and the
ConfigurationBuilder
class in yourStartup
constructor like this:Then you create an
appsettings.xxx.json
file for every environment you need, with "xxx" being the environment name. Note that you can put all global configuration values in your "normal"appsettings.json
file and only put the environment specific stuff into these new files.Now you only need an environment variable called
ASPNETCORE_ENVIRONMENT
with some specific environment value ("live", "staging", "production", whatever). You can specify this variable in your project settings for your development environment, and of course you need to set it in your staging and production environments also. The way you do it there depends on what kind of environment this is.UPDATE: I just realized you want to choose the
appsettings.xxx.json
based on your current build configuration. This cannot be achieved with my proposed solution and I don't know if there is a way to do this. The "environment variable" way, however, works and might as well be a good alternative to your approach.You may use conditional compilation:
Just an update for .NET core 2.0 users, you can specify application configuration after the call to
CreateDefaultBuilder
:1.Create multiple appSettings.$(Configuration).jsons like appSettings.staging.json appSettings.production.json
2.Create a pre-build event on the project which copies the respective file to appSettings.json like this
copy appSettings.$(Configuration).json appSettings.json
3.Use Only appSettings.json in your Config Builder
In ASP.NET Core you should rather use EnvironmentVariables instead of build configuration for proper appsettings.json
Right click on you project > Properties > Debug > Environment Variables
ASP.NET Core will take proper appsettings.json file.
Now you can use that Environment Variable like this:
If you do it @Dmitry 's way, you will have problems eg. when overriding appsettings.json values on Azure.
You can add the configuration name as the
ASPNETCORE_ENVIRONMENT
in thelaunchSettings.json
as below