dotnet run O dotnet watch con entorno de desarrollo desde la línea de comandos?


Estoy usando el comando dotnet watch para ejecutar asp.net proyecto básico. Sin embargo, por defecto, está recogiendo el Production como un entorno.

He probado ambas opciones usando:

1) > dotnet watch ASPNETCORE_ENVIRONMENT=Development

2) > dotnet run ASPNETCORE_ENVIRONMENT=Development

Pero todavía recoge la producción como un entorno.

Nota: En visual studio la variable de entorno se establece en las propiedades del proyecto como Desarrollo de forma predeterminada y la ejecución desde visual studio selecciona esa variable.

La pregunta es: Cómo ejecutar el proyecto dotnet core en desarrollo desde la línea de comandos ¿usando cualquiera?:

1) dotnet run
2) dotnet watch
Author: Set, 2016-05-19

5 answers

ASPNETCORE_ENVIRONMENT es una variable de entorno (y AFAIK) no un conmutador a la cli dotnet.

Así que lo que haría es configurarlo antes de usar la herramienta:

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

rem Unix
$ export ASPNETCORE_ENVIRONMENT=Development
$ dotnet ...
 80
Author: Christian.K,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-19 12:09:07

No tiene para usar variables de entorno si ajusta cómo el WebHostBuilder procesa su configuración. Esto es simplemente el valor predeterminado para dotnet new -t web. Por ejemplo, si desea poder establecer el entorno predeterminado en "desarrollo" en lugar de producción y facilitar la sobreescritura del entorno en la línea de comandos, podría hacerlo modificando el código normal Program.cs a partir de este ...

    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();
    }

... en algo como esto ...

    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();
    }

Haciendo esto, el las variables de entorno seguirían funcionando, pero se puede sobrescribir en la línea de comandos sin dependencias de terceros, así:

dotnet run environment=development
dotnet run environment=staging

Esto es realmente lo que los generadores yeoman hacen.

 25
Author: Technetium,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-20 16:23:06

También puede establecer la variable en línea cuando llame a dotnet:

ASPNETCORE_ENVIRONMENT=Development dotnet run

He encontrado que esto es genial para scripts NPM, pero siempre debe ser llamado justo antes de dotnet, por ejemplo:

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

Nota: Esto solo funciona en OS X o Linux; para una solución multiplataforma, puede usar cross-env:

npm install cross-env -D

Luego cambie los scripts a:

{
  ...
  "scripts": {
    "start": "cd MyApp && cross-env ASPNETCORE_ENVIRONMENT=Development dotnet run",
    "watch": "cd MyApp && cross-env ASPNETCORE_ENVIRONMENT=Development dotnet watch"
  },
}
 20
Author: Geir Sagberg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-27 14:56:03

Fuente: https://blogs.msdn.microsoft.com/webdev/2017/02/14/building-single-page-applications-on-asp-net-core-with-javascriptservices/

Estilo añadido.

Si está utilizando PowerShell en Windows, ejecute $Env:ASPNETCORE_ENVIRONMENT = "Development"

Si está utilizando cmd.exe en Windows, ejecute setx ASPNETCORE_ENVIRONMENT "Development" y luego reinicie el símbolo del sistema para que el cambio surta efecto

Si está utilizando Mac/Linux, ejecute export ASPNETCORE_ENVIRONMENT=Development

 8
Author: emragins,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-16 04:50:53

Con el crédito de la respuesta de @Technetium, aquí hay una actualización de dotnetcore 2.0 que funciona muy bien para mí:

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://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.webhost.createdefaultbuilder?view=aspnetcore-2.0 */
                // .UseContentRoot(Directory.GetCurrentDirectory())
                .UseStartup<Startup>()
                .Build();
    }

Gracias de nuevo, @Technetium

 0
Author: Bishop,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-20 14:41:48