How to read App Settings values from Config.json or appsettings.json file in ASP.NET Core

In this article we are going to learn how can we get/read values from config.json or appsettings.json file in Asp.Net core.

Assume you have following settings in your config file

  "MySettings": {
        "key": "12345"

Now, in order to read values from above config file, you need the Configuration object which is available in the namespace 'Microsoft.Extensions.Configuration'. 

Open your startup.cs file and add reference to 'Microsoft.Extensions.Configuration' namespace. You need to use dependency injection to get Configuration object in either your controller or any other class file. Dependency Injection is a built-in feature in .NET core.

To achieve this, add the following line inside ConfigureServices method in startup.cs file.


Now, your new ConfigureServices method will be

public void ConfigureServices(IServiceCollection services)
    services.AddSingleton < IConfiguration > (Configuration);

And, your startup.cs file should look like this

As we added dependency injection for IConfiguration, we can start using it in any controller or any other class.

Reading values from appsettings.json file:

We have to use the constructor injection in any controller for reading values from appsettings.json file. Just add a constructor in your controller which takes IConfiguration interface as input parameter. 
At runtime, when we the controller gets called, this Constructor [MyController(IConfiguration configuration)] will get called and it will get resolved by its concrete class [Configuration] which we have set in Startup class.

 public class MyController : Controller
        private readonly IConfiguration Configuration;

        public MyController(IConfiguration config)
            this.Configuration = config;

Now as we have the reference to Configuration object in our controller we can now read the values from appsettings.json file using following code

            var value = this.config.GetSection("MySettings").GetSection("key").Value;

This is how we set or get values from appsettings.json file in  .Net core projects.

For more useful articles on .Net core visit: Asp.Net core

No comments:

Post a Comment