Telerik blogs
DotNetT2 Light_1200x303

Learn how to fetch properties or values from appsettings.json in .NET Core. We’ll cover it using both IConfiguration and Options Pattern.

Introduction

In this article, we are going to learn how to fetch properties or values from appsettings.json in .NET Core. We'll cover the following topics:

  • Getting values from appsettings.json
    • Using IConfiguration
    • Using Options Pattern
  • Conclusion

Getting Values from appsettings.json

There are one or more ways available to fetch values from appsettings.json file in .NET Core. Following are the two ways we are going to learn:

  • Using IConfiguration
  • Using Options Pattern

Using IConfiguration

The IConfiguration is available in the dependency injection (DI) container, so you can directly access JSON properties by simply injecting IConfiguration in the constructor of a controller or class. It represents a set of key/value application configuration properties.

IConfiguration is used as follows:

  • Create a simple web or web API project in .NET Core
  • Create a controller or use default one
  • Define one readonly property of type IConfiguration and inject in your controller and access JSON properties as follows:
namespace FetchAppsettingsValue.Controllers
{
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Configuration;
    using System.Collections.Generic;

    [Route("api/Configuration")]
    [ApiController]
    public class ConfigurationController : ControllerBase
    {
        private readonly IConfiguration _config;

        public ConfigurationController(IConfiguration config)
        {
            _config = config;
        }

        // GET: api/Configuration
        [HttpGet]
        public IEnumerable<string> Get()
        {
            var result = _config.GetValue<string>("Logging:LogLevel:Default"); // "Information"
            return new string[] { result.ToString() };
        }
    }
}

Using Options Pattern

The first option we discussed is easy to use, but if you want to access multiple values then you need to provide the keys and it shows hard coded values in controllers or classes everywhere. To access multiple values or hierarchy/structured data from appsettings.json, Options Pattern is a good option. It uses classes to represent the group of hierarchy/structured settings.

Options Pattern is used as follows:

  • Create a simple web or web API project in .NET Core
  • Create a controller or use default one
  • Create a class to represent the hierarchy/structured settings (replica of appsettings.json file):
//appsettings.json
{
"Logging": {
"LogLevel": {
  "Default": "Information",
  "Warning": "Warning",
  "Error": "Error"
}
},
"AllowedHosts": "*"
}
//AppSettings.cs
namespace FetchAppsettingsValue
{
    public class AppSettings
    {
        public Logging Logging { get; set; }
        public string AllowedHosts { get; set; }
    }

    public class Logging
    {
        public LogLevel LogLevel { get; set; }
    }

    public class LogLevel
    {
        public string Default { get; set; }

        public string Warning { get; set; }

        public string Error { get; set; }
    }
}
  • Register in the configuration instance in startup.cs class of ConfigureServices method as follows:
public void ConfigureServices(IServiceCollection services)
{
    services.Configure<Logging>(Configuration.GetSection("Logging"));

    services.AddControllers();
}
  • Define one readonly property of type IOptions<T> and inject in your controller and access JSON properties as follows:
namespace FetchAppsettingsValue.Controllers
{
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Options;
    using System.Collections.Generic;

    [Route("api/Option")]
    [ApiController]
    public class OptionController : ControllerBase
    {
        private readonly IOptions<Logging> _logging;
        public OptionController(IOptions<Logging> logging)
        {
            _logging = logging;
        }

        // GET: api/Option
        [HttpGet]
        public IEnumerable<string> Get()
        {
            var result = _logging.Value.LogLevel.Default; // "Information"

            return new string[] { result };
        }
    }
}

You can also download this example from here.

Conclusion

In this article, we discussed how to access settings from appsettings.json in .NET Core using simple examples. If you have any suggestions or queries regarding this article, please contact me.

“Learn It, Share it.”


jeetendra
About the Author

Jeetendra Gund

Jeetendra Gund is a C# Corner MVP as well as the Chapter Leader of C# Corner Pune Chapter. He holds a master’s degree in Computer Science and has worked on several different domains. He has spent six years in grooming his knowledge about Microsoft Technologies and has been sharing his experiences on technologies such as C#.Net, MVC.Net, SQL Server, Entity Framework, AngularJS, JavaScript, HTML, and .NET Static Code Analysis. He is a regular speaker at C# Corner on Microsoft Technologies. Find him: C# Corner, LinkedIn, or Twitter.

Comments

Comments are disabled in preview mode.