Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
334 views
in Technique[技术] by (71.8m points)

c# - How do I transform appsettings.json in a .NET Core MVC project?

I've added additional json config files to my project

appsettings.DEV.json
appsettings.QA.json

and loaded them in the Startup function based on the environment:

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, reloadOnChange: true);
    ...

And I understand how to change the environment: modify the value of the ASPNETCORE_ENVIRONMENT environment variable in project properties. However, there does not appear to be the ability to specify different environment variables depending on the configuration, the dropdownlist is labeled "N/A" and disabled.

The only option I see is to manually change the environment variable value, to change which appsettings are used. I'm sure there is a way to do it automatically, or else how would you ever use CI? (other than using a script to change the environment variable, there has to be an easier way).

The goal here is to setup automated builds and continuous integration for three environments: DEV, QA, and PROD. DEV and QA are on the same machine, so setting the environment variable that specifies the environment manually is not an option.

Project Properties : Debug section

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Determine EnvironmentName from Build Type

For anybody that would like to set the EnvironmentName based on the build type, there is the handy .UseEnvironment(environmentName) on WebHostBuilder (found in Program Main).

As long as the appropriate compilation symbols are set against the build configurations in your project, you can do something like this to determine the EnvironmentName:

public static void Main(string[] args)
{
    string environmentName;
#if DEBUG
    environmentName = "Development";
#elif STAGING
    environmentName = "Staging";
#elif RELEASE
    environmentName = "Production";
#endif

    var host = new WebHostBuilder()
        .UseKestrel()
        .UseEnvironment(environmentName)
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseIISIntegration()
        .UseStartup<Startup>()
        .UseApplicationInsights()
        .Build();

    host.Run();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...