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
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).
<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>
Comments
Post a Comment