How to set Environment Name (IHostingEnvironment.EnvironmentName)?

Multi tool use
How to set Environment Name (IHostingEnvironment.EnvironmentName)?
Default ASP.NET Core web project contain such lines in Startup.cs
:
Startup.cs
if (string.Equals(env.EnvironmentName, "Development", StringComparison.OrdinalIgnoreCase))
{
app.UseBrowserLink();
app.UseErrorPage(ErrorPageOptions.ShowAll);
}
else
{
app.UseErrorHandler("/Home/Error");
}
As I understand, the EnvironmentName is a new way to handle Dev/Production environment. But it doesn't changes on Release build configuration. So what is the way to set a different EnvironmentName
?
EnvironmentName
I can imagine that it should be set in "Commands" as a parameter for server.
UseErrorHandler
UseExceptionHandler
UseErrorPage
UseDeveloperExceptionPage
Officially documented at docs.microsoft.com/aspnet/core/fundamentals/environments
– RickAndMSFT
Dec 22 '17 at 23:02
11 Answers
11
launchsettings.json
At Properties > launchsettings.json
Just like this:
{
"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"
}
}
}
}
It's unclear how the code should know which profile to use when deploying the app, there has to be a missing piece to this that no one for some reason wants to share.
– The Muffin Man
Sep 22 '16 at 22:50
launchSettings.json only meant for Visual Studio: docs.microsoft.com/en-us/aspnet/core/fundamentals/environments
– Granger
Sep 21 '17 at 19:05
After RC2
So what is the way to set a different EnvironmentName?
Set the ASPNETCORE_ENVIRONMENT
environmental variable.
ASPNETCORE_ENVIRONMENT
There are many ways to set that environmental variable. These include a launchSettings.json
profile and other environment-specific ways. Here are some examples.
launchSettings.json
From a console:
// PowerShell
> $env:ASPNETCORE_ENVIRONMENT="Development"
// Windows Command Line
> SET ASPNETCORE_ENVIRONMENT=Development
// Bash
> ASPNETCORE_ENVIRONMENT=Development
From an Azure Web App's App settings:
Before RC2
I can imagine that it should be set in "Commands" as a parameter for server.
That is true. In your project.json, add --ASPNET_ENV production
as a parameter for the server.
--ASPNET_ENV production
"commands": {
"web": "Microsoft.AspNet.Hosting --ASPNET_ENV production --server Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5001"
}
Now when you run dnx . web
from the command line, ASPNET_ENV
will be production
.
dnx . web
ASPNET_ENV
production
Relevant ASP.NET Core Hosting Source Code
The WebHostBuilder
combines "ASPNETCORE_"
with the WebHostDefaults.EnvironmentKey
to make "ASPNETCORE_environment"
. It also supports the legacy keys.
WebHostBuilder
"ASPNETCORE_"
WebHostDefaults.EnvironmentKey
"ASPNETCORE_environment"
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 variable. ASPNET_ENV
and Hosting:Environment
are still supported, but generate a deprecated message warning.
ASPNETCORE_ENVIRONMENT
ASPNET_ENV
Hosting:Environment
https://docs.asp.net/en/latest/migration/rc1-to-rtm.html
Default Value
The default value is "Production" and is set here.
This is the wrong approach, you don't change source code to set an environment variable.. See docs.asp.net/en/latest/fundamentals/diagnostics.html for visual studio 2015. On Azure, you set the environment variable through PS or the app settings page on the portal. @Victor Hurdugaci has the correct answer below.
– RickAndMSFT
May 28 '15 at 19:15
@RickAnd-MSFT I'm not sure how my answer goes against any of your suggestions. First, my answer doesn't change source code, unless you're referring to the
project.json
file, which I'm not considering to be source code. Second, on Azure, my answer suggests using app settings in the portal to set the variable, which is what you also suggest. Your suggestion about using Visual Studio may be fine on Windows, but would not work for those on a Mac or Linux, who aren't able to use Visual Studio 2015, and might be using Visual Studio Code or another text editor. Do correct me if I'm wrong.– Shaun Luttin
May 29 '15 at 3:46
project.json
project.json file is absolutely source code. It doesn't matter how you set the enthronement variable, you can do that in any environment.
– RickAndMSFT
May 30 '15 at 19:08
@RickAnd-MSFT I'm open to that though at present I'm not persuaded. While it's hard to find an authoritative answer, part of the NuGet docs (docs.nuget.org/create/…), for instance, differentiate configuration files from source code. On the other hand, this ASP.NET tutorial (asp.net/identity/overview/features-api/…) says clearly that "the web.config is source code."
– Shaun Luttin
May 30 '15 at 23:51
@RickAnd-MSFT Regardless of whether a config file is considered to be source code or not, it seems appropriate to pass an environmental variable to
dnx
, because dnx
is the .NET Execution Environment. When we're starting up the environment, it seems appropriate to pass environmental variables to it.– Shaun Luttin
May 31 '15 at 0:07
dnx
dnx
You set the environment by defining an environment variable named ASPNET_ENV
.
For example, if you want Release SET ASPNET_ENV=Release
.
ASPNET_ENV
SET ASPNET_ENV=Release
It might also work if you pass ASPNET_ENV=Release
as parameter to the commands but I cannot check it now.
ASPNET_ENV=Release
Here is how it is implemented: https://github.com/aspnet/Hosting/blob/217f9ca3d3ccf59ea06e6555820974ba9c3b5932/src/Microsoft.AspNet.Hosting/ConfigureHostingEnvironment.cs
Do you know how to setup environment variables in the Azure Web App?
– Will Huang
May 3 '15 at 18:43
@WillHuang just add them as AppSettings on the Azure Web App and they will also be added as environment variables.
– Geir Sagberg
May 10 '15 at 7:47
see docs.asp.net/en/latest/fundamentals/diagnostics.html for how to set this in VS2015
– RickAndMSFT
May 28 '15 at 19:15
For a standard windows/IIS from an elevated console:
setx /m ASPNET_ENV UAT
, then iisreset
. SETX makes it permanent, the /m switch makes it a system variable, not a user variable– fiat
Jul 28 '15 at 23:57
setx /m ASPNET_ENV UAT
iisreset
On Azure just set ASPNET_ENV environment variable on web app configuration page.
With your own IIS or other hosting providers - modify web.config to include arguments for "web" command:
<configuration>
<system.webServer>
<handlers>
<add name="httpplatformhandler" path="*" verb="*" modules="httpPlatformHandler" resourceType="Unspecified" />
</handlers>
<httpPlatform processPath="..approotweb.cmd" arguments="--ASPNET_ENV Development" stdoutLogEnabled="false" stdoutLogFile="..logsstdout.log" startupTimeLimit="3600"></httpPlatform>
</system.webServer>
</configuration>
During development (if you can modify source code), you can also create file named Microsoft.AspNet.Hosting.json in a root of your project and set the ASPNET_ENV variable.
{
"ASPNET_ENV": "Test"
}
In ASP.NET Core RC2
the variable name is has been changed to ASPNETCORE_ENVIRONMENT
ASP.NET Core RC2
ASPNETCORE_ENVIRONMENT
e.g. In Windows you can execute this command on the staging server (with admin rights)
SETX ASPNETCORE_ENVIRONMENT "Staging" /M
This only has be be executed once and after that, the server will always be considered as the staging server.
When you do a dotnet run
in the command prompt on that server you will see Hosting environment: Staging
dotnet run
Hosting environment: Staging
I had same problem. To to be independet to enviroment variable and web.config, I created a .json file as (I called 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();
}
}
If you prefer to use VS features (e.g. VS 2017), it is possible to add Environment variables in the Debug tab of project properties. For example, on the latest ASP.NET Core versions (after RC2) you should set ASPNETCORE_ENVIRONMENT
variable.
ASPNETCORE_ENVIRONMENT
As result, the launchSettings.json
file will be created (or updated) in the Properties folder of the corresponding project, so it will be easy to persist this file into your source control solution and share between developers (as opposite to other solutions with SET
/ SETX
commands)
launchSettings.json
SET
SETX
Note: by default, latest ASP.NET Core set the environment to Production. So, you just need to set ASPNETCORE_ENVIRONMENT
to Development
in VS for Debugging purposes (see screenshot above). And sure, when you want to run your code locally with Staging environment, you should set ASPNETCORE_ENVIRONMENT
to Staging
. And finally, when you want to run it on Production environment, just remove this variable or set value to Production
.
ASPNETCORE_ENVIRONMENT
Development
ASPNETCORE_ENVIRONMENT
Staging
Production
To summarize: just make sure Development, Staging or Production values are used (not 'Dev' or anything else) in Debug dialog to set environment and make different extensions working.
See also relevant source code from 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);
}
}
}
If you are thinking that from where it takes this value then as this moment it is static and default value is development.
https://github.com/aspnet/Hosting/blob/dev/src/Microsoft.AspNet.Hosting/HostingEnvironment.cs
When you look at IHostingEnviroment variable type then it is Microsoft.AspNet.Hosting.HostingEnvrioment.
There are two ways you can now change as per dynamic configuration.
You can implement IHostingEnvironment interface and use your own type for that. You can read value from Config file.
You can use interface You can update that variable directly over 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 services in ConfigureServices there is list of service configure by default and one of them is IConfigureHostingEnviroment. Default implementation is internal class so you can not directly access but you can set above key ASPNET_ENV and it read that value.
https://github.com/aspnet/Hosting/blob/dev/src/Microsoft.AspNet.Hosting/ConfigureHostingEnvironment.cs
actually you propose me to set HostingEnvrioment inside the code, whereas it should be set outside, depending on environment (development or production). For now, I can only use an old-fashioned #if DEBUG, as I see
– tsdaemon
Feb 10 '15 at 11:03
You can read that value from any where. You can use Web.config or json file.
– dotnetstep
Feb 10 '15 at 15:21
Why isn't it possible to set ASPNET_ENV directly in config.json?
– Sergey Kandaurov
Oct 21 '15 at 18:41
@SergeyKandaurov, that would essentially create a circular reference. The purpose of ASPNET_ENV is indeed to determine which set of configs to use (e.g. config.Staging.json, config.Production.json, etc).
– codeprose-sam
Dec 12 '15 at 20:25
if you need to set this without changing code - from the command prompt at the root of the project source folder type:
set ASPNET_ENV=Debug
Why no one love this answer?
– MichaelMao
May 11 '16 at 16:23
In VsCode add the following to launch.json
{
"version": "0.2.0",
"configurations": [
{
...
"env": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
...
]
}
Here is one more way to set and switch ASPNETCORE_ENVIRONMENT variable in VS2017 (addtional note to @clark-wu answer):
Note: launchSettings.json has two profiles in my case: "IISExpress" and "Project" where 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/"
}
}
}
Official documentation: You can set ASPNETCORE_ENVIRONMENT to any value, but three values are supported by the framework: Development, Staging, and Production. If ASPNETCORE_ENVIRONMENT isn't set, it defaults to Production.
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
UseErrorHandler
has been renamed toUseExceptionHandler
andUseErrorPage
is nowUseDeveloperExceptionPage
– CrazyPyro
Nov 14 '15 at 2:50