Read environment variables in ASP.NET Core

后端 未结 2 702
臣服心动
臣服心动 2020-12-24 10:32

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 = Prod         


        
相关标签:
2条回答
  • 2020-12-24 10:44

    Your problem is spaces around =.

    This will work (attention to space before closing quote):

    Console.WriteLine(Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT "));
    

    Or remove spaces (better, see comment of @Isantipov below):

    set ASPNETCORE_ENVIRONMENT=Production
    

    P.S. Stop trying to "fix error with space" in this answer! It's not a typo! The real problem in question was with extra space (in SET...), so answer is either use same space in GetEnvironmentVariable() or remove it from SET... command!

    0 讨论(0)
  • 2020-12-24 10:54

    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);
            //<...>
        }
    
        //<...>
    }
    
    0 讨论(0)
提交回复
热议问题