should not net name environmentvariable enabled development deployed aspnetcore_environment asp applications c# asp.net asp.net-core

c# - not - ¿Cómo configurar el nombre del entorno(IHostingEnvironment.EnvironmentName)?



net core appsettings environment (11)

El proyecto web predeterminado ASP.NET Core contiene esas líneas en Startup.cs :

if (string.Equals(env.EnvironmentName, "Development", StringComparison.OrdinalIgnoreCase)) { app.UseBrowserLink(); app.UseDeveloperExceptionPage(ErrorPageOptions.ShowAll); } else { app.UseExceptionHandler("/Home/Error"); }

Según tengo entendido, EnvironmentName es una nueva forma de manejar el entorno Dev / Production. Pero no cambia en la configuración de compilación de lanzamiento. Entonces, ¿cuál es la forma de establecer un EnvironmentName diferente?

Me imagino que debería establecerse en "Comandos" como parámetro para el servidor.


Después de RC2

Entonces, ¿cuál es la forma de establecer un EnvironmentName diferente?

Establezca la variable de entorno ASPNETCORE_ENVIRONMENT .

Hay muchas formas de establecer esa variable ambiental. Estos incluyen un perfil launchSettings.json y otras formas específicas del entorno . Aquí hay unos ejemplos.

Desde una consola:

// PowerShell > $env:ASPNETCORE_ENVIRONMENT="Development" // Windows Command Line > SET ASPNETCORE_ENVIRONMENT=Development // Bash > ASPNETCORE_ENVIRONMENT=Development

Desde la configuración de una aplicación de Azure Web App:

Antes de RC2

Me imagino que debería establecerse en "Comandos" como parámetro para el servidor.

Eso es verdad. En su project.json, agregue la --ASPNET_ENV production como parámetro para el servidor.

"commands": { "web": "Microsoft.AspNet.Hosting --ASPNET_ENV production --server Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5001" }

Ahora cuando ejecutas dnx . web dnx . web desde la línea de comando, ASPNET_ENV será production .

Código fuente de alojamiento principal ASP.NET relevante

WebHostBuilder combina "ASPNETCORE_" con WebHostDefaults.EnvironmentKey para crear "ASPNETCORE_environment" . También es compatible con las claves heredadas.

WebHostDefaults.cs

namespace Microsoft.AspNetCore.Hosting { public static class WebHostDefaults { public static readonly string ApplicationKey = "applicationName"; public static readonly string StartupAssemblyKey = "startupAssembly"; public static readonly string DetailedErrorsKey = "detailedErrors"; public static readonly string EnvironmentKey = "environment"; public static readonly string WebRootKey = "webroot"; public static readonly string CaptureStartupErrorsKey = "captureStartupErrors"; public static readonly string ServerUrlsKey = "urls"; public static readonly string ContentRootKey = "contentRoot"; } }

WebHostBuilder.cs

_config = new ConfigurationBuilder() .AddEnvironmentVariables(prefix: "ASPNETCORE_") .Build(); if (string.IsNullOrEmpty(GetSetting(WebHostDefaults.EnvironmentKey))) { // Try adding legacy environment keys, never remove these. UseSetting(WebHostDefaults.EnvironmentKey, Environment.GetEnvironmentVariable("Hosting:Environment") ?? Environment.GetEnvironmentVariable("ASPNET_ENV")); }

Compatibilidad con versiones anteriores

La clave de entorno se establece con la variable de entorno ASPNETCORE_ENVIRONMENT . ASPNET_ENV y Hosting:Environment aún es compatible, pero genera una advertencia de mensaje en desuso.

https://docs.asp.net/en/latest/migration/rc1-to-rtm.html

Valor por defecto

El valor predeterminado es "Producción" y se establece aquí.


  1. En Azure, simplemente configure la variable de entorno ASPNET_ENV en la página de configuración de la aplicación web.

  2. Con su propio IIS u otros proveedores de alojamiento, modifique web.config para incluir argumentos para el comando "web":

    <configuration> <system.webServer> <handlers> <add name="httpplatformhandler" path="*" verb="*" modules="httpPlatformHandler" resourceType="Unspecified" /> </handlers> <httpPlatform processPath="../approot/web.cmd" arguments="--ASPNET_ENV Development" stdoutLogEnabled="false" stdoutLogFile="../logs/stdout.log" startupTimeLimit="3600"></httpPlatform> </system.webServer> </configuration>

  3. Durante el desarrollo (si puede modificar el código fuente), también puede crear un archivo llamado Microsoft.AspNet.Hosting.json en una raíz de su proyecto y establecer la variable ASPNET_ENV.

    {"ASPNET_ENV": "Prueba"}


Aquí hay una forma más de establecer y cambiar la variable ASPNETCORE_ENVIRONMENT en VS2017 (nota adicional a la respuesta @ clark-wu):

Nota: launchSettings.json tiene dos perfiles en mi caso: "IISExpress" y "Proyecto" donde se define ASPNETCORE_ENVIRONMENT.

{ "iisSettings": { "windowsAuthentication": false, "anonymousAuthentication": true, "iisExpress": { "applicationUrl": "http://localhost:10000/", "sslPort": 0 } }, "profiles": { "IIS Express": { "commandName": "IISExpress", "launchBrowser": true, "launchUrl": "api/entities", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" // <-- related to IIS Express profile } }, "Project": { "commandName": "Project", "launchBrowser": true, "launchUrl": "api/entities", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Production" // <-- related to Project profile }, "applicationUrl": "http://localhost:10000/" } } }

Documentación oficial : puede establecer ASPNETCORE_ENVIRONMENT en cualquier valor, pero el marco admite tres valores: Desarrollo, Puesta en escena y Producción. Si ASPNETCORE_ENVIRONMENT no está configurado, el valor predeterminado es Producción.


En VsCode agregue lo siguiente a launch.json

{ "version": "0.2.0", "configurations": [ { ... "env": { "ASPNETCORE_ENVIRONMENT": "Development" } }, ... ] }


En ASP.NET Core RC2 el nombre de la variable se ha cambiado a ASPNETCORE_ENVIRONMENT

Por ejemplo, en Windows puede ejecutar este comando en el servidor provisional (con derechos de administrador)

SETX ASPNETCORE_ENVIRONMENT "Staging" /M

Esto solo se debe ejecutar una vez y después de eso, el servidor siempre se considerará como el servidor provisional.

Cuando dotnet run una dotnet run en el símbolo del sistema en ese servidor, verá el Hosting environment: Staging



Si está pensando que de dónde toma este valor, en este momento es estático y el valor predeterminado es el desarrollo.

https://github.com/aspnet/Hosting/blob/dev/src/Microsoft.AspNet.Hosting/HostingEnvironment.cs

Cuando observa el tipo de variable IHostingEnviroment, es Microsoft.AspNet.Hosting.HostingEnvrioment.

Hay dos formas en que ahora puede cambiar según la configuración dinámica.

  1. Puede implementar la interfaz IHostingEnvironment y usar su propio tipo para eso. Puede leer el valor del archivo de configuración.

  2. Puede usar la interfaz Puede actualizar esa variable directamente aquí.

    public Startup(IHostingEnvironment env) { // Setup configuration sources. Configuration = new Configuration() .AddJsonFile("config.json").AddEnvironmentVariables(); Configuration.Set("ASPNET_ENV","Your own value"); }

    Si observa los servicios en ConfigureServices, hay una lista de servicios configurados por defecto y uno de ellos es IConfigureHostingEnviroment. La implementación predeterminada es una clase interna, por lo que no puede acceder directamente, pero puede establecer la clave ASPNET_ENV anterior y leer ese valor.

https://github.com/aspnet/Hosting/blob/dev/src/Microsoft.AspNet.Hosting/ConfigureHostingEnvironment.cs


Si prefiere usar las funciones de VS (por ejemplo, VS 2017), es posible agregar variables de entorno en la pestaña Depurar de las propiedades del proyecto. Por ejemplo, en las últimas versiones de ASP.NET Core (después de RC2) debe establecer la variable ASPNETCORE_ENVIRONMENT .

Como resultado, el archivo launchSettings.json se creará (o actualizará) en la carpeta Propiedades del proyecto correspondiente, por lo que será fácil conservar este archivo en su solución de control de origen y compartirlo entre desarrolladores (a diferencia de otras soluciones con SET / Comandos SETX )

Nota: de forma predeterminada, el último ASP.NET Core establece el entorno en Producción. Por lo tanto, solo necesita configurar ASPNETCORE_ENVIRONMENT en Development en VS para fines de depuración (vea la captura de pantalla anterior). Y claro, cuando desee ejecutar su código localmente con el entorno de ensayo, debe establecer ASPNETCORE_ENVIRONMENT en Staging . Y finalmente, cuando desee ejecutarlo en el entorno de Producción, simplemente elimine esta variable o establezca el valor en Production .

Para resumir: solo asegúrese de usar los valores de Desarrollo , Puesta en escena o Producción (no ''Dev'' o cualquier otra cosa) en el cuadro de diálogo Depurar para establecer el entorno y hacer que funcionen las diferentes extensiones.

Consulte también el código fuente relevante de ASP.NET Core:

namespace Microsoft.AspNetCore.Hosting { /// <summary>Commonly used environment names.</summary> public static class EnvironmentName { public static readonly string Development = "Development"; public static readonly string Staging = "Staging"; public static readonly string Production = "Production"; } } namespace Microsoft.AspNetCore.Hosting { /// <summary> /// Extension methods for <see cref="T:Microsoft.AspNetCore.Hosting.IHostingEnvironment" />. /// </summary> public static class HostingEnvironmentExtensions { /// <summary> /// Checks if the current hosting environment name is "Development". /// </summary> /// <param name="hostingEnvironment">An instance of <see cref="T:Microsoft.AspNetCore.Hosting.IHostingEnvironment" />.</param> /// <returns>True if the environment name is "Development", otherwise false.</returns> public static bool IsDevelopment(this IHostingEnvironment hostingEnvironment) { if (hostingEnvironment == null) throw new ArgumentNullException("hostingEnvironment"); return hostingEnvironment.IsEnvironment(EnvironmentName.Development); } /// <summary> /// Checks if the current hosting environment name is "Staging". /// </summary> /// <param name="hostingEnvironment">An instance of <see cref="T:Microsoft.AspNetCore.Hosting.IHostingEnvironment" />.</param> /// <returns>True if the environment name is "Staging", otherwise false.</returns> public static bool IsStaging(this IHostingEnvironment hostingEnvironment) { if (hostingEnvironment == null) throw new ArgumentNullException("hostingEnvironment"); return hostingEnvironment.IsEnvironment(EnvironmentName.Staging); } /// <summary> /// Checks if the current hosting environment name is "Production". /// </summary> /// <param name="hostingEnvironment">An instance of <see cref="T:Microsoft.AspNetCore.Hosting.IHostingEnvironment" />.</param> /// <returns>True if the environment name is "Production", otherwise false.</returns> public static bool IsProduction(this IHostingEnvironment hostingEnvironment) { if (hostingEnvironment == null) throw new ArgumentNullException("hostingEnvironment"); return hostingEnvironment.IsEnvironment(EnvironmentName.Production); } /// <summary> /// Compares the current hosting environment name against the specified value. /// </summary> /// <param name="hostingEnvironment">An instance of <see cref="T:Microsoft.AspNetCore.Hosting.IHostingEnvironment" />.</param> /// <param name="environmentName">Environment name to validate against.</param> /// <returns>True if the specified name is the same as the current environment, otherwise false.</returns> public static bool IsEnvironment(this IHostingEnvironment hostingEnvironment, string environmentName) { if (hostingEnvironment == null) throw new ArgumentNullException("hostingEnvironment"); return string.Equals(hostingEnvironment.EnvironmentName, environmentName, StringComparison.OrdinalIgnoreCase); } } }


Tuve el mismo problema Para ser independiente de la variable de entorno y web.config, creé un archivo .json como (lo llamé envsettings.json ):

{ // Possible string values reported below. // - Production // - Staging // - Development "ASPNETCORE_ENVIRONMENT": "Staging" }

Luego en Program.cs agregué:

public class Program { 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 enviromentValue = envSettings["ASPNETCORE_ENVIRONMENT"].ToString(); var webHostBuilder = new WebHostBuilder() .UseKestrel() .CaptureStartupErrors(true) .UseSetting("detailedErrors", "true") .UseContentRoot(currentDirectoryPath) .UseIISIntegration() .UseStartup<Startup>(); // If none is set it use Operative System hosting enviroment if (!string.IsNullOrWhiteSpace(enviromentValue)) { webHostBuilder.UseEnvironment(enviromentValue); } var host = webHostBuilder.Build(); host.Run(); } }


si necesita configurar esto sin cambiar el código, desde el símbolo del sistema en la raíz del tipo de carpeta de origen del proyecto:

set ASPNET_ENV=Debug


launchsettings.json

En Propiedades> launchsettings.json

Solo así:

{ "iisSettings": { "windowsAuthentication": false, "anonymousAuthentication": true, "iisExpress": { "applicationUrl": "http://localhost:1032/", "sslPort": 0 } }, "profiles": { "IIS Express": { "commandName": "IISExpress", "launchBrowser": true, "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Production" } }, "WebAppNetCore": { "commandName": "Project", "launchBrowser": true, "launchUrl": "http://localhost:5000", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } }, "web": { "commandName": "web", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } }