Reputation: 11304
I have an ASP.NET Core 6 Web API and I am adding a key in appsettings.json
file and trying to read this as environment variable:
var x = Environment.GetEnvironmentVariable("FILE_STORAGE")?.ToUpper();
The value is returned as null
.
I have added below code in the program.cs
file:
var builder = WebApplication.CreateBuilder(args);
var configuration = builder.Configuration;
configuration
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
appsettings.json
:
{
"FILE_STORAGE": "Azure"
}
I know I can read through IConfiguration
(_configuration["FILE_STORAGE"]
), but can I read like Environment.GetEnvironmentVariable("FILE_STORAGE")
?
Upvotes: 2
Views: 1082
Reputation: 24569
Environment.GetEnvironmentVariable
reads the Environment Variable, not the value from settings files, such as appsettings.json!
You should use _configuration["FILE_STORAGE"]
, then it will first try to read your environment variable FILE_STORAGE
, if there is no value - read from appsettings.json
I'd recommend
var value = _configuration.GetValue<string>("FILE_STORAGE");
See Configuration in ASP.NET Core
Upvotes: 3