Shoe Diamente
Shoe Diamente

Reputation: 794

Specify boolean variable using environment variables in .NET Core

Given the following program:

    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration((builderContext, config) =>
                {
                    var env = builderContext.HostingEnvironment;
                    config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true)
                        .AddEnvironmentVariables(prefix: "Prefix_");
                })
                .UseStartup<Startup>();
    }

and a configuration usually defined in appsettings.json as:

{
    "SomeSection": {
        "SomeOption": true
    }
}

is there a way to override it as environment variable (using the method specified in the docs)?


I've tried with (I'm on macOS, but the same problem also happens in Linux and Docker Compose):

export Prefix_SomeSection__SomeOption=true

but it's parsed as a string and it can't convert it to a boolean. The same method works with every other non boolean option, which seems to imply that there's some undocumented way to define a variable as a boolean.

Upvotes: 9

Views: 13523

Answers (1)

Shoe Diamente
Shoe Diamente

Reputation: 794

I was setting the environment variables with docker-compose.yml like this:

version: '3.4'

services:

  server:
    environment:
      Prefix_SomeSection__SomeOption: true

the error that I got was related to docker-compose.yml, not .NET Core, and it was:

contains true, which is an invalid type, it should be a string, number, or a null

The solution is to just wrap that true into a string like this:

version: '3.4'

services:

  server:
    environment:
      Prefix_SomeSection__SomeOption: "true"

Upvotes: 9

Related Questions