asp.netasp.net-coreasp.net-core-mvckestrel-http-server

Read environment variables in ASP.NET Core


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?


Solution

  • 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