How to Read from appsettings.json in ASP.NET Core C#?

Read and get configuration values from appsettings.json file in ASP.NET Core C#. I will show you the example in Console App. Below is the code snippet.

using Microsoft.Extensions.Configuration;
using System;
using System.IO;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            var builder = new ConfigurationBuilder()
                              .SetBasePath(Directory.GetCurrentDirectory())
                              .AddJsonFile("appsettings.json");
            var config = builder.Build();
            Console.WriteLine($"{config["name"]} --> {config["email"]}");
        }
    }
}

Below is the sample appsettings.json file I have used for this demo.

{
  "name": "JD Bots",
  "email": "info@jd-bots.com"
}

My project structure is same as below.

Below is the output I got on the console.

Error and Exceptions you might get with their Fixes

  1. ‘ConfigurationBuilder’ does not contain a definition for ‘SetBasePath’ and no accessible extension method ‘SetBasePath’ accepting a first argument of type ‘ConfigurationBuilder’ could be found -> [Fixed] ‘ConfigurationBuilder’ does not contain a definition for ‘SetBasePath’.
  2. The configuration file ‘appsettings.json’ was not found and is not optional -> [Fixed] The configuration file ‘appsettings.json’ was not found and is not optional.

Thank you All!!! Hope you find this useful.


Leave a Reply

Up ↑

Discover more from JD Bots

Subscribe now to keep reading and get access to the full archive.

Continue reading