In Asp.net Core 6 Program.cs File, What Is The Method To Utilize Appsettings.json In C#?

To use the appsettings.json file in the Program.cs file in ASP.NET Core 6, you need to configure the configuration builder and load the appsettings.json file. Here are the steps to use the appsettings.json in the Program.cs file:

  1. Open the Program.cs file in your ASP.NET Core 6 project.

  2. In the CreateHostBuilder method, modify the code to configure the configuration builder and load the appsettings.json file. You can add the following code snippet just before ConfigureWebHostDefaults:

var config = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json")
    .Build();
  1. Now, you can access the configuration values from the appsettings.json file. For example, you can get a value using the GetValue method:
var myValue = config.GetValue<string>("MySetting");

Make sure to replace MySetting with the actual key from your appsettings.json file.

Here’s the complete modified CreateHostBuilder method:

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            var config = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json")
                .Build();

            var myValue = config.GetValue<string>("MySetting");

            webBuilder.UseStartup<Startup>();
        });

Note that this approach allows you to access the configuration values in the Program.cs file. However, the recommended way to access configuration values in the application is through dependency injection in the Startup.cs file.

About the Author Rex

I'm a passionate tech blogger with an insatiable love for programming! From my early days tinkering with code, I've delved into web dev, mobile apps, and AI. Sharing insights and tutorials with the world is my joy, connecting me to a global community of like-minded tech enthusiasts. Python holds a special place in my heart, but I embrace all challenges. Constantly learning, I attend tech conferences, contribute to open-source projects, and engage in code review sessions. My ultimate goal is to inspire the next generation of developers and contribute positively to the ever-evolving tech landscape. Let's code together!