Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is appsettings.json loaded in ASP.NET Core

The NET Core 2.x Web API project template provides a Program.cs and Startup.cs (among other things by default).

If you put a breakpoint inside the constructor of Startup, and add a watch you can see the values loaded from appsettings.json.

enter image description here

Startup.cs and Program.cs are not explicitly loading appsettings.json, so it must be happening in the call to CreateDefaultBuilder or Build in Program.

public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();
}

I have looked the Microsoft source code on https://github.com/aspnet/Configuration and https://github.com/aspnet/Hosting, in particular the WebHostBuilder, but I can't see where it happens.

Where is the code that loads the appsettings.json?

like image 742
Bryan Avatar asked Jun 13 '18 21:06

Bryan


People also ask

How does Appsettings json work?

The appsettings. json file is generally used to store the application configuration settings such as database connection strings, any application scope global variables, and much other information.

Where does Appsettings json go?

appsettings. json is one of the several ways, in which we can provide the configuration values to ASP.NET core application. You will find this file in the root folder of our project.


1 Answers

appsettings.json is loaded by the call to CreateDefaultBuilder located in Microsoft.AspNetCore.WebHost.

 //snip
 config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
 //snip

Source code available on GitHub - https://github.com/aspnet/AspNetCore/blob/master/src/DefaultBuilder/src/WebHost.cs#L165

like image 189
Bryan Avatar answered Sep 21 '22 10:09

Bryan