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.
Environment variables can never be a boolean, they are always a string (or not present).
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.
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With