Automatically set appsettings.json for dev and rel

2020-01-29 03:42发布

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?

7条回答
霸刀☆藐视天下
2楼-- · 2020-01-29 04:23

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.

Declaration of the environment variable in launch.json

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

Project view of appsettings JSON files

And finally, configure it to your StartUp class, like below:

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 I run it from the command line, like this:

dotnet run --environment "Development"

where "Development" is the name of my environment.

查看更多
登录 后发表回答