liveBook · Manning

AddJsonFile()

As explained in ASP.NET Core in Action, 3e

AddJsonFile() is a .NET configuration extension method that adds a JSON file as a configuration source.

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

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains filenames, optional loading, provider precedence, and immediate ConfigurationManager loading, but not provider implementation internals.
Examples
Demonstrates clearing default sources, adding appsettings.json, and exposing configuration key-value pairs through an endpoint.
What you can do after
Operate/configure it by adding an optional JSON provider and retrieving the resulting settings through IConfiguration.
How it connects
Connects JSON files with ConfigurationManager, IConfiguration, environment variables, command-line arguments, and User Secrets.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.