c# - .NET 5 WorkerService HostingEnvironment.IsDevelopment() 在环境变量 ASPNETCORE_ENVIRONMENT 设置为 Development 时返回 false
问题描述
正如标题所说,我创建了一个新的 .NET 5 WorkerService 但是当我调用HostingEnvironment.IsDevelopment()
它时,即使环境变量ASPNETCORE_ENVIRONMENT
设置为Development
.
Program.cs 看起来像这样:
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostContext, builder) =>
{
if (hostContext.HostingEnvironment.IsDevelopment())
{
builder.AddUserSecrets<Program>();
}
})
.ConfigureServices((hostContext, services) =>
{
var configuration = hostContext.Configuration;
var settings = new MyAppSettings();
configuration.GetSection("MyApp").Bind(settings);
services.AddSingleton(settings);
services.AddHttpClient();
services.AddHttpClient<MyAppHttpClient>();
services.AddHostedService<Worker>();
})
.ConfigureLogging(logging =>
{
logging.AddEventLog(eventLogSettings =>
{
eventLogSettings.SourceName = "MyAppBooker";
});
});
}
环境变量在调试属性下设置,如下所示:
我可以确认环境变量也设置正确。
我正在遵循“在开发中安全存储应用程序机密”的指南,代码来自那里。
我也尝试过设置NETCORE_ENVIRONMENT
,但没有任何区别。
https://github.com/dotnet/aspnetcore/issues/4150
考虑到我认为的方法描述,它应该可以工作:
检查当前托管环境名称是否为 Development。
根据文档IHostingEnvironment.EnvironmentName Property
应该这样做:
获取或设置环境的名称。主机自动将此属性设置为“ASPNETCORE_ENVIRONMENT”环境变量的值,或任何其他配置源中指定的“环境”。
鉴于此描述,我不明白为什么程序设置hostContext.HostingEnvironment.EnvironmentName
为Production
在 Debug 中本地运行。
解决方案
Thanks to @Jack A. The missing link was DOTNET_ENVIRONMENT
with value Development
in Environment variables. The error occurred because launchSettings.json
was not in Git and therefore the original Environment variable was never set.
推荐阅读
- javascript - 循环中的Javascript条件
- go - 通过字符在字符串中的位置获取字符
- javascript - Pagespeed 评分低 - 我错过了什么?
- spring - 如何在 JAXRSClientFactoryBean 或 JAXRSClientFactory 中添加标头
- python - 马氏距离在 Pytorch 中返回 NaN
- visual-studio-code - 为 vscode 扩展的用户添加任务到 tasks.json
- mysql - 在 MySQL 中使用窗口函数移动平均
- pytorch - PyTorch 张量的“大于”运算符“>”是什么意思?
- javascript - 获取两个 Date 对象之间的持续时间(以小时和分钟为单位) - JavaScript
- docker - 无法从 docker 容器连接到互联网