Bert Sinnema
Bert Sinnema

Reputation: 329

Environment Variable not found in dotnet core 2 app

I am implementing an Azure Key Vault to protect my app secrets from my development teams. To authenticate against Azure Key Vault in production I want to set some environment variables like KV_APP_ID and KV_APP_SECRET, which I have done here (I have also tried User Variables):

Environment variables

Now in my Program.cs file of my .NET CORE 2.0 app I want to read those variables, but I get nulls.

public static IWebHost BuildWebHost(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((context, config) =>
        {
            if (!context.HostingEnvironment.IsProduction()) return;

            config.SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", false)
                .AddEnvironmentVariables();

            var builtConfig = config.Build();

            config.AddAzureKeyVault(

                $"https://{Environment.GetEnvironmentVariable("KV_NAME")}.vault.azure.net/",
                Environment.GetEnvironmentVariable("KV_APP_ID"),
                Environment.GetEnvironmentVariable("KV_APP_SECRET"),
                new PrefixKeyVaultSecretManager(Environment.GetEnvironmentVariable("KV_PREFIX")));
            })
            .UseStartup<Startup>()
            .Build();

I had a look at the documentation but I can't seem to find why my environment variables are not loaded. I could add it to launchSettings.json but I don't want to have the contents of the variables to end up in source control.

Any thoughts?

Upvotes: 1

Views: 1009

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239460

Well, there's really not enough here to answer your question, but I can make a pretty good guess based on the assumption that you're hosting this in IIS.

When hosting in IIS, in order for your application to see environment variables, the App Pool it's running under must be configured to "Load User Profile". In IIS, go to the advanced settings of the App Pool for your site and you'll see a setting in that list called "Load User Profile". Set that to true, and then recycle the App Pool.

Upvotes: 1

Related Questions