.NET 5 WorkerService HostingEnvironment.IsDevelopment() returns false 而环境变量 ASPNETCORE_ENVIRONMENT 设置为开发

.NET 5 WorkerService HostingEnvironment.IsDevelopment() returns false while Environment Variable ASPNETCORE_ENVIRONMENT is set to Development

正如标题所说,我创建了一个新的 .NET 5 WorkerService 但是当我调用 HostingEnvironment.IsDevelopment() 它 returns false 即使环境变量 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";
                });
            });
}

环境变量在调试属性下设置如下:

我可以确认环境变量也设置正确。

我正在遵循“开发中应用机密的安全存储”指南,代码来自那里。

https://docs.microsoft.com/en-us/aspnet/core/security/app-secrets?view=aspnetcore-5.0&tabs=windows#access-a-secret

我也试过设置NETCORE_ENVIRONMENT,但没用。

https://github.com/dotnet/aspnetcore/issues/4150

根据我认为的方法描述应该可以工作:

Checks if the current hosting environment name is Development.

https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.hosting.hostingenvironmentextensions.isdevelopment?view=aspnetcore-5.0

根据文档 IHostingEnvironment.EnvironmentName Property 应该这样做:

Gets or sets the name of the environment. The host automatically sets this property to the value of the "ASPNETCORE_ENVIRONMENT" environment variable, or "environment" as specified in any other configuration source.

https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.hosting.ihostingenvironment.environmentname?view=aspnetcore-5.0

鉴于此描述,我不明白为什么程序在 Debug 中本地将 hostContext.HostingEnvironment.EnvironmentName 设置为 Production 运行。

感谢@Jack A。缺少的 link 是 DOTNET_ENVIRONMENT,环境变量中的值为 Development。发生错误是因为 launchSettings.json 不在 Git 中,因此从未设置原始环境变量。