Optional appsettings.local.json in (new format) visual studio project
For .NET 6, you can use this.
Also make sure, you git ignore appsettings.local.json
to avoid check-in sensitive information like password and secrets.
var builder = WebApplication.CreateBuilder(args);
// Add configurations
builder.Host.ConfigureAppConfiguration((hostingContext, config) =>
{
config.Sources.Clear();
var env = hostingContext.HostingEnvironment;
config.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) //load base settings
.AddJsonFile("appsettings.local.json", optional: true, reloadOnChange: true) //load local settings
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) //load environment settings
.AddEnvironmentVariables();
if (args != null)
{
config.AddCommandLine(args);
}
});
For .Net Core >2.1 you can simply chain the extension method ConfigureAppConfiguration(Action<WebHostBuilderContext, IConfigurationBuilder> configureDelegate)
to your WebHost. Here is an example:
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.AddJsonFile(
"appsettings.Local.json",
optional: true,
reloadOnChange: true);
})
// ...
And of course ignore the appsettings.Local.json in your .gitignore.
With v2 this is dead simple.
- Add an
appsettings.local.json
to your project (it should nest itself below the mainappsettings.json
file). - Add
appsettings.local.json
to your.gitignore
In your
startup.cs
within the constructor do the following:public class Startup { public IConfigurationRoot Configuration { get; } public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) //load base settings .AddJsonFile("appsettings.local.json", optional: true, reloadOnChange: true) //load local settings .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) //load environment settings .AddEnvironmentVariables(); Configuration = builder.Build(); } /* * rest of your startup.cs */ }