I have generated a new web project. it seems that in .net core 3.1 the appSettings.jsons were generated and working fine. the problem is that they are loaded and controlled by the runtime and not me. So I cant invoke AddEnvironmentVariables
Where is the right place to call AddEnvironmentVariables
in such case?
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
}
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
var environment = Environment. GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"); var builder = new ConfigurationBuilder() . AddJsonFile($"appsettings. json", true, true) .
AddEnvironmentVariables(IConfigurationBuilder, String) Adds an IConfigurationProvider that reads configuration values from environment variables with a specified prefix.
Open project properties by right clicking on the project in the solution explorer and select Properties. This will open properties page. Click on Debug tab and you will see Environment Variables as shown below. You may change the value as per your need.
The documentation is probably the best place to read up on all configuration methods that are available. To answer your specific question, the extension method you're after is defined on IConfigurationBuilder
, therefore it has to be invoked before you build your host like so:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.ConfigureAppConfiguration(configurationBuilder => { configurationBuilder.AddEnvironmentVariables(); }) // here's where you add another `EnvironmentVariablesConfigurationSource`
;
a default EnvironmentVariablesConfigurationSource
is already being injected for you by ConfigureWebHostDefaults
, so you will end up having two providers.
I am assuming you want to inject a customised configuration instead, so you might need to remove the default one from the list first:
.ConfigureAppConfiguration(configurationBuilder =>
{
configurationBuilder.Sources.Remove(
configurationBuilder.Sources.First(source =>
source.GetType() == typeof(EnvironmentVariablesConfigurationSource))); //remove the default one first
configurationBuilder.AddEnvironmentVariables();
})
hopefully this gives you a starting point to explore further
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