【发布时间】:2021-08-04 20:58:32
【问题描述】:
正如标题所说,我创建了一个新的 .NET 5 WorkerService,但是当我调用 HostingEnvironment.IsDevelopment() 时,即使环境变量 ASPNETCORE_ENVIRONMENT 设置为 Development,它也会返回 false。
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 中。
【问题讨论】:
-
您是否确认您的环境变量与 properties\launchSettings.json 中的内容没有冲突?另外,您是否尝试过 DOTNET_ENVIRONMENT?当我创建一个新的工作人员服务时,这就是它放入 launchSettings.json 的内容。
-
@JackA。是的 -
"DOTNET_ENVIRONMENT": "Development"在launchSettings.json。编辑:这是错误!我在一台没有launchSettings.json文件的计算机上,因为它在 Git 中被忽略了。非常感谢!