[c#] how to set ASPNETCORE_ENVIRONMENT to be considered for publishing an asp.net core application?

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

This question is related to c# asp.net-core environment-variables

The answer is


Other option that we use in our projects in order to be able to set the environment per-site is to add a Parameters.xml file to the project with the following content:

<parameters>
      <parameter name="IIS Web Application Name" defaultValue="MyApp" tags="IisApp" />    
      <parameter name="Environment" description="Environment" tags="">
        <parameterEntry kind="XmlFile" scope="Web.config"  match="/configuration/location/system.webServer/aspNetCore/environmentVariables/environmentVariable[@name='ASPNETCORE_ENVIRONMENT']/@value" />
      </parameter>    
</parameters>

The Build Action for this file is Content and the Copy Action is Copy If Newer so it will be part of the package to deploy.

Then, to deploy the package and set the environment, in the Release, under the "WinRM - IIS Web App Deployment" task (it works just as well when using the "IIS web app deploy" task), we set additional arguments for msdeploy:

-setParam:kind=ProviderPath,scope=contentPath,value="MySite" -setParam:name="Environment",value="Stage"

This way we can have multiple releases, all using the same artifact, but deployed as different environments.


  1. Create your appsettings.*.json files. (Examples: appsettings.Development.json, appsettings.Staging.json, appsettings.Production.json)

  2. Add your variables to those files.

  3. Create a separate publish profile for each environment, like you normally would.

  4. Open PublishProfiles/Development.pubxml (naming will be based on what you named the Publish Profile).

  5. Simply add a tag to the PublishProfile to set the EnvironmentName variable, the appsettings.*.json file naming convention does the rest.

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

Reference: https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/visual-studio-publish-profiles?view=aspnetcore-3.1

Refer to the “Set the Environment” section.


I found it working for me by setting this variable directly on Azure platorm (if you use it). Just select your web app -> configuration -> application settings and add the variable and its value, then press Save button.


Option1:

To set the ASPNETCORE_ENVIRONMENT environment variable in windows,

Command line - setx ASPNETCORE_ENVIRONMENT "Development"

PowerShell - $Env:ASPNETCORE_ENVIRONMENT = "Development"

For other OS refer this - https://docs.microsoft.com/en-us/aspnet/core/fundamentals/environments

Option2:

If you want to set ASPNETCORE_ENVIRONMENT using web.config then add aspNetCore like this-

<configuration>
  <!--
    Configure your application settings in appsettings.json. Learn more at http://go.microsoft.com/fwlink/?LinkId=786380
  -->
  <system.webServer>
    <handlers>
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
    </handlers>
    <aspNetCore processPath=".\MyApplication.exe" arguments="" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false">
      <environmentVariables>
        <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" />
      </environmentVariables>
    </aspNetCore>
  </system.webServer>
</configuration>

With the latest version of dotnet cli (2.1.400 or greater), you can just set this msbuild property $(EnvironmentName) and publish tooling will take care of adding ASPNETCORE_ENVIRONMENT to the web.config with the environment name.

Also, XDT support is available starting 2.2.100-preview1.

Sample: https://github.com/vijayrkn/webconfigtransform/blob/master/README.md


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


This variable can be saved in json. For example envsettings.json with content as below

  {
   // Possible string values reported below. When empty it use ENV variable value or 
     // Visual Studio setting.
     // - Production
     // - Staging
     // - Test
     // - Development

   "ASPNETCORE_ENVIRONMENT": "Development"
  }

Later modify your program.cs as below

  public class Program
  {
    public static IConfiguration Configuration { get; set; }
    public static void Main(string[] args)
    {
        var currentDirectoryPath = Directory.GetCurrentDirectory();
        var envSettingsPath = Path.Combine(currentDirectoryPath, "envsettings.json");
        var envSettings = JObject.Parse(File.ReadAllText(envSettingsPath));
        var environmentValue = envSettings["ASPNETCORE_ENVIRONMENT"].ToString();

        var builder = new ConfigurationBuilder()
               .SetBasePath(Directory.GetCurrentDirectory())
               .AddJsonFile("appsettings.json");

        Configuration = builder.Build();
          var webHostBuilder = new WebHostBuilder()
            .UseKestrel()
            .CaptureStartupErrors(true)
            .UseContentRoot(currentDirectoryPath)
            .UseIISIntegration()
            .UseStartup<Startup>();

        // If none is set it use Operative System hosting enviroment
        if (!string.IsNullOrWhiteSpace(environmentValue))
        {
            webHostBuilder.UseEnvironment(environmentValue);
        }

        var host = webHostBuilder.Build();

        host.Run();
     }
 }

This way it will always be included in publish and you can change to required value according to environment where website is hosted. This method can also be used in console app as the changes are in Program.cs


Simple way to set it in visual studio IDE.

Project > Properties> Debug > Environment variables

enter image description here


This is how we can set it in run-time:

public class Program
{
    public static void Main(string[] args)
    {
        Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "Development");

        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();
}

You should follow the instructions provided in the documentation, using the web.config.

<aspNetCore processPath="dotnet"
        arguments=".\MyApp.dll"
        stdoutLogEnabled="false"
        stdoutLogFile="\\?\%home%\LogFiles\aspnetcore-stdout">
  <environmentVariables>
    <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Production" />
    <environmentVariable name="CONFIG_DIR" value="f:\application_config" />
  </environmentVariables>
</aspNetCore>

Note that you can also set other environment variables as well.

The ASP.NET Core Module allows you specify environment variables for the process specified in the processPath attribute by specifying them in one or more environmentVariable child elements of an environmentVariables collection element under the aspNetCore element. Environment variables set in this section take precedence over system environment variables for the process.


I know this is an old post however thought I'd throw my simple solution into the mix since no one has suggested it.

I use the current directory to determine the current environment then flip the connection string and environment variable. This works great so long as you have a naming convention for your site folders such as test/beta/sandbox.

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        var dir = Environment.CurrentDirectory;
        string connectionString;

        if (dir.Contains("test", StringComparison.OrdinalIgnoreCase))
        {
            connectionString = new ConnectionStringBuilder(server: "xxx", database: "xxx").ConnectionString;
            Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "Development");
        }
        else
        {
            connectionString = new ConnectionStringBuilder(server: "xxx", database: "xxx").ConnectionString;
            Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "Production");
        }

        optionsBuilder.UseSqlServer(connectionString);
        optionsBuilder.UseLazyLoadingProxies();
        optionsBuilder.EnableSensitiveDataLogging();
    }

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net-core

dotnet ef not found in .NET Core 3 How to use Bootstrap 4 in ASP.NET Core ASP.NET Core - Swashbuckle not creating swagger.json file Getting value from appsettings.json in .net core .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Automatically set appsettings.json for dev and release environments in asp.net core? Get ConnectionString from appsettings.json instead of being hardcoded in .NET Core 2.0 App Unable to create migrations after upgrading to ASP.NET Core 2.0 EF Core add-migration Build Failed ASP.NET Core form POST results in a HTTP 415 Unsupported Media Type response

Examples related to environment-variables

Using Environment Variables with Vue.js Adding an .env file to React Project Is there any way to set environment variables in Visual Studio Code? Test process.env with Jest How to set environment variables in PyCharm? ARG or ENV, which one to use in this case? how to set ASPNETCORE_ENVIRONMENT to be considered for publishing an asp.net core application? What is a good practice to check if an environmental variable exists or not? Passing bash variable to jq Tensorflow set CUDA_VISIBLE_DEVICES within jupyter