ASP .NET Core read environment variables

≯℡__Kan透↙ 提交于 2019-11-28 23:34:08

问题


Running my ASP.NET Core-app 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 app does not seem to be able to read environment variables.

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

returns null

What am I missing?


回答1:


Your problem is spaces around =.

This will work:

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

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

set ASPNETCORE_ENVIRONMENT=Production



回答2:


This should really be a comment to this answer by @Dmitry (but 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 aspnet 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 docs article

Ans also I guess if you'd like to stay purely inside aspnet core paradigm, you'd want to use IHostingEnvironment.Environment(see docs) property instead of reading from Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") directly (although the fromer 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);
        //<...>
    }

    //<...>
}


来源:https://stackoverflow.com/questions/37387235/asp-net-core-read-environment-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!