95

I am using dotnet watch command to run asp.net core project. However, by default, it is picking up the Production as an environment.

I have tried both options using:

1) > dotnet watch ASPNETCORE_ENVIRONMENT=Development

2) > dotnet run ASPNETCORE_ENVIRONMENT=Development

But it still picks up production as an environment.

Note: In visual studio environment variable is set in project properties as Development by default and running from visual studio picks that variable.

Question is: How to run dotnet core project in development from command line using either?:

1) dotnet run
2) dotnet watch
Set
  • 47,577
  • 22
  • 132
  • 150
Nexus23
  • 6,195
  • 9
  • 50
  • 67

7 Answers7

133

ASPNETCORE_ENVIRONMENT is an environment variable (and AFAIK) not a switch to the dotnet cli.

So what you would do is set it prior to using the tool:

rem Windows
C:\> set ASPNETCORE_ENVIRONMENT=Development
C:\> dotnet ...

rem Unix
$ export ASPNETCORE_ENVIRONMENT=Development
$ dotnet ...
Christian.K
  • 47,778
  • 10
  • 99
  • 143
  • 3
    Have set an environment variable ASPNETCORE_ENVIRONMENT and its value to be Development, but still in command line it is picking up hosting environment as production. Wondering how .net core sets this variable when running with visual studio by setting this in project properties. Isn't there a commandline switch? In Asp.Net Rc1 we used to pass it in web command of project properties like --ASPNET_ENV Development. – Nexus23 May 19 '16 at 13:38
  • Thanks, I was setting the variable in separate window, works fine as you suggested. :) – Nexus23 May 20 '16 at 13:30
  • @Christian.k I think this will set entire environment to `Development` and cannot see any changes at application level. What if 1. Want to change only application specific 2. Any way to change from application, not expecting from project properties, thru some other way if I am building application using **Visual Studio Code** – Avi Kenjale Jun 07 '16 at 14:34
  • @AviKenjale that Dennis entirely ob where you set the variable. If you set it n a shell / cmd.exe it will only be visible to whatever commands or programs you start from that shell, no influence on other apps started from other shells with (possibly) differently set env vars. – Christian.K Jun 07 '16 at 20:10
  • Great ! It is working as you said. However, still 1. How can change default port 5000 to something else using command line? 2. Is this `set` command same as `launchSettings.json`? Basically I am more interested to set environment variables, Launch URLs thru my Ubuntu's Visual Studio Code or terminal. – Avi Kenjale Jun 07 '16 at 20:26
  • @AviKenjale please ask a new questions using the "Ask Question" button at the top of the SO page. It is not useful to offload them into the comments, where they are less visible for other users and where there are insufficient capabilities to properly provide an answer. – Christian.K Jun 08 '16 at 03:51
  • Isn't it really possible to do it without setting the ENV variable? Passing an argument to DOTNET executable is more "systematic" IMHO. – Skorunka František Jun 25 '16 at 10:57
  • @SkorunkaFrantišek it's possible with a few minor changes. I wrote up an answer to explain how. – Technetium Aug 24 '16 at 19:55
  • @Toolkit: I'm not the developer and I - of course - had no saying in this, merely saying how it is. Having that said, _overwriting_ configuration file settings with environment variables is not retarded at all, but typical in many software products (albeit I'd agree a command line option in addition would be nice). Also this is not a "global" environment variable. As you can see, it is set in the shell (instance) from where you start the app. You could set it globally, but that is not the idea. Just as it is with many environment variable "solutions" you have the choice and can take a bad one. – Christian.K Jan 18 '21 at 05:46
  • @Toolkit It should not be a production issue to set to "Development" mode. If you don't like the solution MS has taken, open an issue with them. Cheers. – Christian.K Jan 18 '21 at 05:47
  • @Christian.K, so if it is not a "global" environment variable, but a shell one, I was wrong. It is an acceptable solution. Sorry mate – Toolkit Jan 18 '21 at 13:25
  • you can set the environment from the CLI using "dotnet watch run --environment Development". – David Mays Jun 28 '22 at 20:44
  • In powershell you can use `$Env:ASPNETCORE_ENVIRONMENT="Development"` – 我零0七 Mar 02 '23 at 08:19
39

You don't have to use environment variables if you adjust how the WebHostBuilder processes its configuration. This is merely the default for dotnet new -t web. For example, if you wanted to be able to set the default environment to "development" instead of production and facilitate overriding the environment in the command line, you could do that by modifying the normal Program.cs code from this ...

    public static void Main(string[] args) {
        var host = new WebHostBuilder()
            .UseKestrel()
            .UseUrls("http://0.0.0.0:5000")
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>()
            .Build();

        host.Run();
    }

... into something like this ...

    private static readonly Dictionary<string, string> defaults =
        new Dictionary<string, string> {
            { WebHostDefaults.EnvironmentKey, "development" }
        };

    public static void Main(string[] args) {
        var configuration =
            new ConfigurationBuilder()
                .AddInMemoryCollection(defaults)
                .AddEnvironmentVariables("ASPNETCORE_")
                .AddCommandLine(args)
                .Build();

        var host =
            new WebHostBuilder()
                .UseConfiguration(configuration)
                .UseKestrel()
                .UseUrls("http://0.0.0.0:5000")
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>()
                .Build();

        host.Run();
    }

Doing this, the environment variables would still work, but you can override it on the command line without any third-party dependencies, like so:

dotnet run environment=development
dotnet run environment=staging

This is actually what the yeoman generators do.

Technetium
  • 5,902
  • 2
  • 43
  • 54
  • 1
    It's worth nothing that due to an implementation detail of Microsoft's environment variable configuration package, the `ASPNETCORE_` prefix is stripped in the eyes of all other pieces of configuration. This is why you do not include the prefix on the command line. – Technetium Aug 24 '16 at 19:52
  • 4
    It's also worth nothing that you'll need to add the `Microsoft.Extensions.Configuration.CommandLine` package as a dependency to your project if you had not yet done so. It will contain the `AddCommandLine()` extension method. – Technetium Aug 26 '16 at 20:26
  • Exactly what is needed! Thank you – Yury Scherbakov Sep 16 '16 at 14:59
  • 1
    It seems the environment parameter doesn't exist anymore. It doesn't work for me and I can't find it in the docs: https://learn.microsoft.com/de-de/dotnet/articles/core/tools/dotnet-run – lex82 Apr 20 '17 at 15:01
  • it never existed out-of-the-box, @lex82. My answer describes how to change `Program.cs` to make this possible - not that it's some kind of default functionality. – Technetium Apr 20 '17 at 16:21
  • ok, sorry. I should have read your answer properly instead of just skimming it ;-) – lex82 Apr 20 '17 at 16:35
  • Just had this question: https://stackoverflow.com/questions/45264806/cant-make-a-function-call-in-in-spite-of-the-using-statement-and-extension-need?noredirect=1#comment77492507_45264806 (should have read the comments of your answer). Now it runs, but any idea why `dotnet run environment=development` would still run in production mode? – MrJalapeno Jul 23 '17 at 13:09
  • Nevermind, forgot to add `.UseConfiguration(configuration)` to webhostbuilder. – MrJalapeno Jul 23 '17 at 13:28
  • 1
    As an update to dotnetcore 2.0, the `Microsoft.Extensions.Configuration.CommandLine` package doesn't seem necessary now. – Bishop Apr 20 '18 at 13:24
  • Seems that `dotnet run environment=staging` does not work any more. However I can change the environment name using slightly different command line, like `dotnet project1.dll --environment Production` where `Project1.dll` is a ASP.NET Core project built for .NET Core 3.1 – oleksa Feb 06 '20 at 14:19
  • @oleksa: Did you plug in the `AddCommandLine(args)` configuration parsing, or are you trying it without updating your `Program.cs` file? – Technetium Feb 06 '20 at 16:08
  • I'm using `.AddJsonFile` and `.AddEnvironmentVariables()` only. Should I use `AddCommandLine` to make `environment=development` key works? – oleksa Feb 07 '20 at 08:21
  • Yes, but for your host configuration as opposed to your application configuration. Those aren't the same thing. If you look above, I provided configuration to the WebHostBuilder which includes `AddCommandLine(args)`, not configuration to the application. – Technetium Feb 07 '20 at 16:37
  • This MS doco contradicts, says the command line uses double dash --environment - but for me right now, neither works... https://learn.microsoft.com/en-us/aspnet/core/fundamentals/environments?view=aspnetcore-6.0#set-environment-on-the-command-line – PandaWood Sep 09 '22 at 03:09
35

You can also set the variable inline when calling dotnet:

ASPNETCORE_ENVIRONMENT=Development dotnet run

I have found this is great for NPM scripts, but must always be called right before dotnet, e.g.:

{
  ...
  "scripts": {
    "start": "cd MyApp && ASPNETCORE_ENVIRONMENT=Development dotnet run",
    "watch": "cd MyApp && ASPNETCORE_ENVIRONMENT=Development dotnet watch"
  },
}

Note: This only works in OS X or Linux; for a cross-platform solution, you can use cross-env:

npm install cross-env -D

Then change the scripts to:

{
  ...
  "scripts": {
    "start": "cd MyApp && cross-env ASPNETCORE_ENVIRONMENT=Development dotnet run",
    "watch": "cd MyApp && cross-env ASPNETCORE_ENVIRONMENT=Development dotnet watch"
  },
}
Geir Sagberg
  • 9,632
  • 8
  • 45
  • 60
  • 1
    @Konstantin You're right, it does not. I imagine adding https://www.npmjs.com/package/cross-env will do the trick though, e.g. "cd MyApp && cross-env ASPNETCORE_ENVIRONMENT=Development dotnet run". – Geir Sagberg Aug 10 '16 at 13:06
28

Check documentation

https://learn.microsoft.com/en-us/dotnet/core/tools/dotnet-run?tabs=netcore21

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/environments?view=aspnetcore-2.1

dotnet run --launch-profile EnvironmentsSample

launchSettings.json

{ 
  "profiles": {    
    "EnvironmentsSample": {
      "commandName": "Project",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Staging"
      },
      "applicationUrl": "http://localhost:54340/"
    },   
  }
}
RouR
  • 6,136
  • 3
  • 34
  • 25
22

From Building Single Page Applications on ASP.NET Core with JavaScriptServices (styling added):

If you’re using PowerShell in Windows, execute $Env:ASPNETCORE_ENVIRONMENT = "Development"

If you’re using cmd.exe in Windows, execute setx ASPNETCORE_ENVIRONMENT "Development", and then restart your command prompt to make the change take effect

If you’re using Mac/Linux, execute export ASPNETCORE_ENVIRONMENT=Development

Community
  • 1
  • 1
emragins
  • 4,607
  • 2
  • 33
  • 48
8

To set from CLI using dotnet run or dotnet watch:

dotnet run --environment Development

dotnet watch run --environment Development

David Mays
  • 466
  • 4
  • 14
  • I believe you're right, however when I type: dotnet run --environment Production - it still outputs "Hosting environment: Development", so not sure how to convince anyone this actually works – PandaWood Sep 09 '22 at 03:13
  • @PandaWood could you somehow have a typo somewhere? If I type: "dotnet run --environment noob" I receive "info: Microsoft.Hosting.Lifetime[0] Hosting environment: noob" but do get "development" if I misspell environment. You may also have accidentally manually overridden the hierarchy of where .NET looks for variables as these can be changed in Program.cs if you really wanted to. – David Mays Sep 13 '22 at 17:16
  • 1
    The generated file Properties\launchSettings.json appears to override the environment variable(s) and command line parameter. – user423430 Oct 21 '22 at 20:33
  • Works for .net core 6, just create a new appsettings.Custom.json, then run `dotnet watch run --environment Custom` – Ron Michael Jun 02 '23 at 06:12
1

With credit to @Technetium 's answer, here's an update to dotnetcore 2.0 that works really well for me:

public class Program
    {
        private static readonly Dictionary<string, string> defaults = new Dictionary<string, string> {{ WebHostDefaults.EnvironmentKey, "Development" }};
        private static IConfiguration config;
        public static void Main(string[] args)
        {
            config = new ConfigurationBuilder()
                .AddInMemoryCollection(defaults)
                .AddEnvironmentVariables("ASPNETCORE_")
                .AddCommandLine(args)
                .Build();
            BuildWebHost(args).Run();
        }
public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseConfiguration(config)
                /* Following setting already accounted for in CreateDefaultBuilder() : https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.webhost.createdefaultbuilder?view=aspnetcore-2.0 */
                // .UseContentRoot(Directory.GetCurrentDirectory())
                .UseStartup<Startup>()
                .Build();
    }

Thanks again, @Technetium

Bishop
  • 1,011
  • 8
  • 9