dotnet run OR dotnet watch with development environment from command line?
Asked Answered
S

7

100

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
Swarey answered 19/5, 2016 at 11:59 Comment(2)
Is it just me, or none of the answers below worked!Marco
Mm, I was using powershell, turned to command prompt and it worked... wonder whyMarco
B
139

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 ...
Barrada answered 19/5, 2016 at 12:9 Comment(13)
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.Swarey
Thanks, I was setting the variable in separate window, works fine as you suggested. :)Swarey
@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 CodeIncestuous
@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.Barrada
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.Incestuous
@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.Barrada
Isn't it really possible to do it without setting the ENV variable? Passing an argument to DOTNET executable is more "systematic" IMHO.Lilith
@SkorunkaFrantišek it's possible with a few minor changes. I wrote up an answer to explain how.Pam
@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.Barrada
@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.Barrada
@Christian.K, so if it is not a "global" environment variable, but a shell one, I was wrong. It is an acceptable solution. Sorry mateIntellect
you can set the environment from the CLI using "dotnet watch run --environment Development".Nae
In powershell you can use $Env:ASPNETCORE_ENVIRONMENT="Development"Livia
P
41

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.

Pam answered 24/8, 2016 at 19:51 Comment(14)
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.Pam
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.Pam
Exactly what is needed! Thank youCauvery
It seems the environment parameter doesn't exist anymore. It doesn't work for me and I can't find it in the docs: learn.microsoft.com/de-de/dotnet/articles/core/tools/dotnet-runPowell
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.Pam
ok, sorry. I should have read your answer properly instead of just skimming it ;-)Powell
Just had this question: #45265306 (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?Foolery
Nevermind, forgot to add .UseConfiguration(configuration) to webhostbuilder.Foolery
As an update to dotnetcore 2.0, the Microsoft.Extensions.Configuration.CommandLine package doesn't seem necessary now.Prine
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.1Lalita
@oleksa: Did you plug in the AddCommandLine(args) configuration parsing, or are you trying it without updating your Program.cs file?Pam
I'm using .AddJsonFile and .AddEnvironmentVariables() only. Should I use AddCommandLine to make environment=development key works?Lalita
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.Pam
This MS doco contradicts, says the command line uses double dash --environment - but for me right now, neither works... learn.microsoft.com/en-us/aspnet/core/fundamentals/…Bissonnette
O
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"
  },
}
Order answered 27/6, 2016 at 19:5 Comment(1)
@Konstantin You're right, it does not. I imagine adding npmjs.com/package/cross-env will do the trick though, e.g. "cd MyApp && cross-env ASPNETCORE_ENVIRONMENT=Development dotnet run".Order
O
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/"
    },   
  }
}
Ossein answered 30/10, 2018 at 14:51 Comment(1)
this works for me -> "dotnet run --launch-profile EnvironmentsSample"Articulator
K
24

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

Katheleenkatherin answered 16/5, 2017 at 4:50 Comment(0)
N
10

To set from CLI using dotnet run or dotnet watch:

dotnet run --environment Development

dotnet watch run --environment Development

Nae answered 28/6, 2022 at 20:42 Comment(5)
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 worksBissonnette
@Bissonnette 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.Nae
The generated file Properties\launchSettings.json appears to override the environment variable(s) and command line parameter.Lambart
Works for .net core 6, just create a new appsettings.Custom.json, then run dotnet watch run --environment CustomAmphoteric
dotnet watch run --project ProjectNameGreatly
P
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

Prine answered 20/4, 2018 at 14:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.