Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 525
Shoe Diamente Avatar asked Nov 13 '19 14:11

Shoe Diamente


People also ask

Can an environment variable be a boolean?

Environment variables can never be a boolean, they are always a string (or not present).

How do you assign a boolean to a variable?

You can use the bool method to cast a variable into Boolean datatype. In the following example, we have cast an integer into boolean type. You can also use the bool method with expressions made up of comparison operators. The method will determine if the expression evaluates to True or False.

How do you write a boolean method in C#?

Syntax: public bool Equals (bool obj); Here, obj is a boolean value to compare to this instance. Return Value: This method returns true if obj has the same value as this instance otherwise it returns false.


1 Answers

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"

like image 63
Shoe Diamente Avatar answered Oct 27 '22 04:10

Shoe Diamente