Running my ASP.NET Core application using DNX, I was able to set environment variables from the command line and then run it like this:
set ASPNET_ENV = Production
dnx web
Using the same approach in 1.0:
set ASPNETCORE_ENVIRONMENT = Production
dotnet run
does not work - the application does not seem to be able to read environment variables.
Console.WriteLine(Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"));
returns null
What am I missing?
Open project properties by right clicking on the project in the solution explorer and select Properties. This will open properties page. Click on Debug tab and you will see Environment Variables as shown below. You may change the value as per your need.
Environment Variables are one of the sources from which ASP.NET Core reads the configuration values. In this tutorial, let us learn how to set Environment Variables in Windows, Mac, Linux, IIS Server, Visual Studio, Visual Studio Code & dotnet run. We also learn how to read them in ASP.NET core.
On the Windows taskbar, right-click the Windows icon and select System. In the Settings window, under Related Settings, click Advanced system settings. On the Advanced tab, click Environment Variables.
Your problem is spaces around =
.
This will work (attention to space before closing quote):
Console.WriteLine(Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT "));
The space after ASPNETCORE_ENVIRONMENT
in this code is not a typo! The problem in the question was having extra space (in SET...), so you must use the same space in GetEnvironmentVariable().
As noted by Isantipov in a comment, an even better solution is to remove the spaces entirely from the SET command:
set ASPNETCORE_ENVIRONMENT=Production
This should really be a comment to this answer by @Dmitry (but it is too long, hence I post it as a separate answer):
You wouldn't want to use 'ASPNETCORE_ENVIRONMENT '
(with a trailing space) - there are features in ASP.NET Core which depend on the value of 'ASPNETCORE_ENVIRONMENT'
(no trailing space) - e.g. resolving of appsettings.Development.json
vs appsettings.Production.json
. (e.g. see Working with multiple environments documentation article
And also I guess if you'd like to stay purely inside ASP.NET Core paradigm, you'd want to use IHostingEnvironment.Environment
(see documentation) property instead of reading from Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")
directly (although the former is of course set from the latter). E.g. in Startup.cs
public class Startup
{
//<...>
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
Console.WriteLine("HostingEnvironmentName: '{0}'", env.EnvironmentName);
//<...>
}
//<...>
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With