how to set ASPNETCORE_ENVIRONMENT to be considered for publishing an asp.net core application?

Dario picture Dario · Jan 9, 2017 · Viewed 128.7k times · Source

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 .pubxml file
  • in launchSettings.json
  • in project.json

Answer

Abhinav Galodha picture Abhinav Galodha · Jan 30, 2019

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>

Above code would add the environment name as Development for 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 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 the Properties/PublishProfiles/{profilename.pubxml} This will set the Environment name in web.config when the project is published. More Details here

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

3. Command line options using dotnet publish

Additionaly, we can pass the property EnvironmentName as a command line option to the dotnet publish command. Following command would include the environment variable as Development in the web.config file.

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