C# – How to set ASPNETCORE_ENVIRONMENT to be considered for publishing an ASP.NET Core application

asp.net-corecenvironment-variables

When I publish my ASP.NET Core web application to my local file system, it always takes the production-config and the ASPNETCORE_ENVIRONMENT variable with the value = "Production".

How and where do I have to set the value of the ASPNETCORE_ENVIRONMENT variable so that it will be considered not only for debugging, but also for the publishing? I already tried the following options without success:

  • in windows settings
  • in file .pubxml file
  • in file launchSettings.json
  • in file project.json

Best Answer

Other than the options mentioned above, there are a couple of other solutions.

1. Modifying the project file (.CsProj) file

MSBuild supports the EnvironmentName property which can help to set the right environment variable as per the environment you wish to deploy. The environment name would be added in the web.config during the publish phase.

Simply open the project file (*.csProj) and add the following XML.

<!-- Custom property group added to add the environment name during publish

     The EnvironmentName property is used during the publish
     for the environment variable in web.config
-->
<PropertyGroup Condition=" '$(Configuration)' == '' Or '$(Configuration)' == 'Debug'">
  <EnvironmentName>Development</EnvironmentName>
</PropertyGroup>

<PropertyGroup Condition=" '$(Configuration)' != '' AND '$(Configuration)' != 'Debug' ">
  <EnvironmentName>Production</EnvironmentName>
</PropertyGroup>

The above code would add the environment name as Development for a debug configuration or if no configuration is specified. For any other configuration, the environment name would be Production in the generated web.config file. More details are here.

2. Adding the EnvironmentName property in the publish profiles.

We can add the <EnvironmentName> property in the publish profile as well. Open the publish profile file which is located at Properties/PublishProfiles/{profilename.pubxml}. This will set the environment name in web.config when the project is published. More details are here.

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

3. Command line options using dotnet publish

Additionally, we can pass the property EnvironmentName as a command-line option to the dotnet publish command. The following command includes the environment variable as Development in the web.config file.

dotnet publish -c Debug -r win-x64 /p:EnvironmentName=Development