How to set environment name (IHostingEnvironment.EnvironmentName)?

The ASP.NET Core web project, by default, contains the following lines in Startup.cs :

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

As I understand it, EnvironmentName is a new way to handle development and production environments. But that will not change in the release build configuration. So how do you set up another EnvironmentName ?

I can imagine that it should be installed in the "Commands" as a parameter for the server.

+55
c # asp.net-core
Feb 01 '15 at 0:44
source share
11 answers

launchsettings.json

In properties> launchsettings.json

Similar:

  { "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" } } } } 
+12
Sep 11 '16 at 16:14
source share

After RC2

So what is the way to set a different environment name?

Set the environment variable ASPNETCORE_ENVIRONMENT .

There are many ways to set this environment variable. These include the launchSettings.json profile and other environmental-related methods . Here are some examples.

On the console:

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

From the settings of the Azure Web App:

Set environment name in Azure

Before RC2

I can imagine that it should be installed in the "Commands" as a parameter for the server.

It's right. In the project.json file, add --ASPNET_ENV production as the parameter for the server.

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

Now when you start dnx . web dnx . web from the command line, ASPNET_ENV will be production .

Corresponding source code for ASP.NET core hosting

WebHostBuilder combines "ASPNETCORE_" with WebHostDefaults.EnvironmentKey to make "ASPNETCORE_environment" . It also supports obsolete keys.

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

backward compatibility

The environment key is set with the ASPNETCORE_ENVIRONMENT environment ASPNETCORE_ENVIRONMENT . ASPNET_ENV and Hosting:Environment are still supported, but generate a warning with an outdated message.

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

Default value

The default value is Production and is set here.

+68
May 19 '15 at
source share

You set up the environment by defining an environment variable named ASPNET_ENV . For example, if you want Release SET ASPNET_ENV=Release .

It may also work if you pass ASPNET_ENV=Release as a parameter to the commands, but I cannot check it now.

Here's how it is implemented: https://github.com/aspnet/Hosting/blob/217f9ca3d3ccf59ea06e6555820974ba9c3b5932/src/Microsoft.AspNet.Hosting/ConfigureHostingEnvironment.cs

+15
Feb 01 '15 at 5:18
source share

I had the same problem. To be independent of the environment variable and web.config, I created the .json file as (I named it envsettings.json):

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

Then in Program.cs I added:

 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(); } } 
+5
Feb 01 '17 at 19:35
source share

If you prefer to use VS functions (for example, VS 2017), you can add environment variables on the Debug tab of the project properties. For example, in recent versions of ASP.NET Core (after RC2), you must set the ASPNETCORE_ENVIRONMENT variable.

enter image description here

As a result, the launchSettings.json file will be created (or updated) in the Properties folder of the corresponding project, so it will be easy to save this file in your original control solution and share it between developers (as opposed to other solutions with SET / SETX )

Note. By default, the latest ASP.NET Core sets up the environment in Production. Thus, you just need to set ASPNETCORE_ENVIRONMENT in Development in VS for debugging purposes (see screenshot above). And of course, if you want to run your code locally using the Staging environment, you must set ASPNETCORE_ENVIRONMENT to Staging . And finally, when you want to run it in a production environment, just delete this variable or set the Production value.

To summarize: just make sure that the Development, Staging, or Production values ​​are used (not "Dev" or something else) in the Debug dialog box to set up your environment and create different extensions.

See also the corresponding source code from the ASP.NET kernel:

 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); } } } 
+4
May 29 '17 at 9:40 pm
source share

If you think that where it takes this value from, then as this moment it is static, and the default value is development.

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

When you look at the type of the variable IHostingEnviroment, it is Microsoft.AspNet.Hosting.HostingEnvrioment.

Now you can change two ways to change the dynamic configuration.

  • You can implement the IHostingEnvironment interface and use your own type for this. You can read the value from the Config file.

  • You can use the interface. You can update this variable directly here.

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

    If you look at the services in ConfigureServices, the list of service settings is configured by default, and one of them is IConfigureHostingEnviroment. The default implementation is an inner class, so you cannot access it directly, but you can set the ASPNET_ENV key above and read that value.

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

+3
Feb 01 '15 at 5:31
source share
  • On Azure, just set the ASPNET_ENV environment variable on the web application configuration page.

  • With your own IIS or other hosting providers - modify web.config to include arguments for the "web" command:

     <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> 
  • During development (if you can change the source code), you can also create a file called Microsoft.AspNet.Hosting.json in the root directory of your project and set the ASPNET_ENV variable.

    {"ASPNET_ENV": "Test"}

+3
Oct 21 '15 at 19:15
source share

In ASP.NET Core RC2 the variable name has been changed to ASPNETCORE_ENVIRONMENT

eg. On Windows, you can run this command on an intermediate server (with administrator privileges)

 SETX ASPNETCORE_ENVIRONMENT "Staging" /M 

This will be done only once and after that the server will always be considered an intermediate server.

When you run dotnet run at a command prompt on this server, you will see Hosting environment: Staging

+3
Jun 16 '16 at 9:26
source share

if you need to install this without changing the code, from the command line in the root directory of the project’s source folder:

 set ASPNET_ENV=Debug 
+2
Apr 03 '16 at 9:25
source share

In VsCode, add the following to launch.json

 { "version": "0.2.0", "configurations": [ { ... "env": { "ASPNETCORE_ENVIRONMENT": "Development" } }, ... ] } 
0
Jan 14 '17 at 0:44
source share

Here is another way to set and switch the ASPNETCORE_ENVIRONMENT variable in VS2017 (note to @ clark-wu answer):

enter image description here

Note. In my case, launchSettings.json has two profiles: "IISExpress" and "Project", in which ASPNETCORE_ENVIRONMENT is defined.

 { "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/" } } } 

White papers : ASPNETCORE_ENVIRONMENT can be set to any value, but the platform supports three values: development, preparation, and production. If ASPNETCORE_ENVIRONMENT is not set, Production is used by default.

0
Jul 02 '18 at 22:33
source share



All Articles