首页 > 解决方案 > .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";
                });
            });
}

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

在此处输入图像描述

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

在此处输入图像描述

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

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

考虑到我认为的方法描述,它应该可以工作:

检查当前托管环境名称是否为 Development。

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

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

获取或设置环境的名称。主机自动将此属性设置为“ASPNETCORE_ENVIRONMENT”环境变量的值,或任何其他配置源中指定的“环境”。

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

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

在此处输入图像描述

标签: c#.net.net-core.net-5

解决方案


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.


推荐阅读