在没有前缀的通用主机中读取环境变量 (.NET)

Read Environment Variables in generic host without prefix (.NET)

我想在 .NET 5 或 .NET 6 中读取我的自定义环境变量。我遇到了一些问题。我只能读取带有 DOTNET_ASPNETCORE_ 前缀的环境变量:

例如,我看不懂 MyKey=MyValue:

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((hostContext,configuration) =>
        {
            string myKey = hostContext.Configuration["MyKey"];
            configuration.AddJsonFile($"Airlines/{myKey}.json");
        })
        .ConfigureServices((hostContext, services) =>
        {
            services.AddRabbitMQ();
            services.AddSingleton<NiraAvailableFlightsConsumer>();

            services.AddOptions<AirlineOptions>()
                    .Bind(hostContext.Configuration);
        });

默认生成器的 documentation 表示:

Loads host configuration from:

  • Environment variables prefixed with DOTNET_.

因此您的变量不会作为主机上下文配置的一部分读取。您可以通过将 ConfigureHostConfiguration 调用添加到您的启动来告诉构建器加载所有环境变量:

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureHostConfiguration(config =>
        {
            config.AddEnvironmentVariables();
        })
        .ConfigureAppConfiguration((hostContext, configuration) =>
        {
            string myKey = hostContext.Configuration["MyKey"];
            configuration.AddJsonFile($"Airlines/{myKey}.json");
        })
        .ConfigureServices((hostContext, services) =>
        {
            ....
        });