AddJsonFile() adds a JSON file as a configuration source in an ASP.NET Core application. Provide the filename, and optionally allow the application to continue when the file is missing. section 10.2.1
Load an optional JSON file
WebApplicationBuilder builder = WebApplication.CreateBuilder(args); builder.Configuration.Sources.Clear(); builder.Configuration.AddJsonFile("appsettings.json", optional: true); WebApplication app = builder.Build(); app.MapGet("/", () => app.Configuration.AsEnumerable()); app.Run(); Here, clearing the sources removes the providers configured by default. AddJsonFile() then adds appsettings.json, while optional: true prevents a missing file from causing FileNotFoundException. section 10.2.1
Configuration providers contribute key-value pairs to ConfigurationManager. Provider order matters: later providers replace earlier values for matching settings while preserving unique settings. In .NET 6 and .NET 7, ConfigurationManager makes values available immediately; ConfigurationBuilder requires Build(). section 10.2.1 section 10.5
Listing 10.3 Loading appsettings.json by clearing the configuration sources
WebApplicationBuilder builder = WebApplication.CreateBuilder(args); builder.Configuration.Sources.Clear(); #1 builder.Configuration.AddJsonFile("appsettings.json", optional: true); #2 WebApplication app = builder.Build(); app.MapGet("/", () => app.Configuration.AsEnumerable()); #3 app.Run(); #1 Clears the providers configured by default in WebApplicationBuilder #2 Adds a JSON configuration provider, providing the name of the configuration file #3 Returns all the configuration key-value pairs for display purposes
View the complete listing for clearing default providers, adding appsettings.json, and displaying all loaded configuration values. section 10.2.1
