I'm just getting started with .net Core 2.1 and I have written a custom ConfigurationProvider that loads my sensitive configuration from a separate file. This works great with a hard-coded path but I also want the location of the file to be stored in configuration. If I try to access the appsettings config during the setup of my provider the values aren't there. Presumably this is because I am in the configuration phase still. Is there a way of accessing them or failing that is there a way to add another config provider inside Startup.cs instead of Program.cs?
This is what I am trying to do:
public static IWebHostBuilder CreateWebHostBuilder(string[] args)
{
return WebHost.CreateDefaultBuilder(args)
.ConfigureLogging((hostingContext, logging) =>
{
logging.ClearProviders();
logging.AddConsole();
logging.AddFile(opts =>
{
hostingContext.Configuration.GetSection("FileLoggerOptions").Bind(opts);
});
})
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath);
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
config.AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", optional: true);
config.AddEncryptedFile(hostingContext.Configuration["SecureSettingsFile"], true, true);
})
.UseStartup<Startup>();
}
As you can see I am able to access the config in the logging config but not the app config. My provider is the AddEncryptedFile
bit and hostingContext.Configuration["SecureSettingsFile"]
should read the value from appsettings.json.
The only configuration available at this stage is Environment variables and I don't really want to use those as the server has about 30 websites on it.
Is what I am trying do possible or will I have to use an Environment variable or store my encrypted config in the same location as my website?
thanks
You'll need to use a ConfigurationBuilder
to initially just read appsettings.json
, and use the output of the builder to do your full configuration. Something like this:
.ConfigureAppConfiguration((hostingContext, config) =>
{
var baseConfig = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var secureSettingsFile = baseConfig.GetValue<string>("SecureSettingsFile");
/* ... */
config.AddEncryptedFile(secureSettingsFile, true, 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