.NET Core 环境变量返回 null [英] .NET Core environment variable returns null

查看:49
本文介绍了.NET Core 环境变量返回 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 .NET Core 控制台应用程序.我正在尝试使用以下代码检索环境变量.

var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

然而,变量环境"总是返回空值.我通过

设置了环境变量ASPNETCORE_ENVIRONMENT"<块引用>

控制面板 -> 系统属性 -> 环境变量 -> 系统变量

我也尝试使用命令 set ASPNETCORE_ENVIRONMENT=development 设置环境变量,但这也不起作用.当我在 Visual Studio 中调试代码 (F5) 时,该变量始终返回 null.我已经确保在我设置变量的地方或在我阅读它的代码中没有任何空格.有什么我遗漏的吗?

解决方案

我认为只有当您通过 dotnet run 启动控制台应用程序时,设置环境变量才有效:

<块引用>

当 ASPNETCORE_ENVIRONMENT 环境变量被全局设置时,它对 dotnet 运行在之后打开的任何命令窗口中生效值已设置.

来自:

I have a .NET Core console application. I'm trying to retrieve the environment variable using the below code.

var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

However, the variable "environment" always return null. I set the environment variable "ASPNETCORE_ENVIRONMENT" through

Control Panel -> System Properties -> Environment Variables -> System Variables

I also tried setting the environment variable using the command set ASPNETCORE_ENVIRONMENT=development, but that also did not work. When I debug the code (F5) in Visual Studio, the variable always return null. I have made sure that there aren't any spaces where I set the variable, or in my code where I read it. Is there anything I'm missing?

解决方案

I think setting the environment variable would only work if you started your console application via dotnet run:

When the ASPNETCORE_ENVIRONMENT environment variable is set globally, it takes effect for dotnet run in any command window opened after the value is set.

From: Use multiple environments in ASP.NET Core


Try setting it it your Debug properties.

Right click your project in Visual Studio and select PropertiesDebug.

Set the environment variable as shown in the image below.

这篇关于.NET Core 环境变量返回 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆