ASPNETCORE_ENVIRONMENT in Published Project

Typical Program.cs

        public Startup(IHostingEnvironment env)
        {
            // https://blog.elmah.io/config-transformations-in-aspnetcore/
            // https://andrewlock.net/how-to-set-the-hosting-environment-in-asp-net-core/
            // https://github.com/aspnet/Hosting/issues/863
            // For dev, please remove or rename appsettings.production.json, so that it's not used

            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true)
                .AddEnvironmentVariables();
            Configuration = builder.Build();
        }


Please note:

  • ASPNETCORE_ENVIRONMENT settings in Properties\launchSettings.json only affects debugging by using Visual Studio or C:\projectfolder>dotnet run.
  • For a published project, ASPNETCORE_ENVIRONMENT is hardwired to Production. No way to change it.

About optional in AddJsonFile

if opional:true, the file will be used if it exists;
if opional:false, the file must exist else exception will be thrown.

Suggestion for development

Please remove or rename appsettings.production.json, so that the production database will not be used in development.

Add the following to /Properties/PublishProfiles/dev.pubxml:

<PropertyGroup>
...
    <EnvironmentName>Development</EnvironmentName>
...

This will set  the environment variables in the generated web.config as follows:

        <environmentVariables>
          <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" />
        </environmentVariables>

This way the appsettings.development.json will be used (rather than appsettings.production.json).



Comments

Popular posts from this blog

Use GnuPG Tools or C# Code for PGP Encryption and Signature

Errors in Net Core Add-Migration

Set up Visual Studio 2017 for .Net Core Application Development