Access Value from appsettings.json File in Class File Using C#.Net

How to access value from appsettings.json file in a class file or class library project in asp.net core mvc application using c#.net.
In today's article I will show you how you can access the appsettings.json file configuration value with defined key in your class file or in class library file. So, for this first we will create a new asp.net core mvc application and add sone value in it.

Appsettings.json value

After this we need to install a NuGet package named as Microsoft.Extensions.Configuration.Json NuGet package. With the help of this NuGet package we will be able to parse the appsettings.json data into object.

Microsoft.Extensions.Configuration.Json NuGet package

After installing NuGet package we need to add a class file and add the below code in it.
namespace Project
{
    public static class TestClassFile
    {
        public static string GetValue()
        {
            var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json", optional: false);
            IConfiguration config = builder.Build();
            string value = config.GetValue<string>("key:Value");
            return value;
        }
    }} 
Here in above code, I have first read the appsettings.json and converted into an object. Here I have created a method which will read the value as per given key.  Here the passed key is key:Value.  Now let's access the class method to check the output. Here we can see that the break point execute.

Appsettings.json value

Here in above code, we can see that we are able to get the defined value. Please let me know you view on this.


Post a Comment