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?
I have added screenshots of a working environment, because it cost me several hours of R&D.
First, add a key to your launch.json
file.
See the below screenshot, I have added Development
as my environment.
Then, in your project, create a new appsettings.{environment}.json
file that includes the name of the environment.
In the following screenshot, look for two different files with the names:
appsettings.Development.Json
appSetting.json
And finally, configure it to your StartUp
class like this:
public Startup(IHostingEnvironment env)
{
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();
}
And at last, you can run it from the command line like this:
dotnet run --environment "Development"
where "Development"
is the name of my environment.