Get values from configuration file appsettings.json in ASP.NET Core 3.1 MVC

2 minute read

Introduction

In a previous post below, I explained how to get the value from appsettings.json in ASP.NET Core in .NET Core 1.1.

-Getting values from the configuration file appsettings.json in ASP.NET Core MVC

This time, I will explain how to get the value from appsettings.json in ASP.NET Core in .NET Core 3.1.
The basic method is almost the same.

Definition of appsettings.json

Suppose you define appsettings.json as follows:

appsettings.json


{
  "UserSettings": {
    "IsDemoMode": false,
    "DefaultUser": {
      "Name": "Ashikaga Yoshinori",
      "Age": 48
    }
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }
}

Getting configuration information in IConfiguration

The configuration information is injected with dependencies without any action, so you can get the configuration information from the controller with IConfiguration.

HomeController.cs



public class HomeController : Controller
{
    private readonly IConfiguration _configuration;
    private readonly ILogger<HomeController> _logger;
    

    public HomeController(IConfiguration configuration, ILogger<HomeController> logger)
    {
            this._configuration = configuration;            
            this._logger = logger;
    }

    public IActionResult Index()
    {   
        //Boolean load
        bool isDemoMode = this._configuration.GetValue<bool>("UserSettings:IsDemoMode");
        //The loading of string values can be specified in the indexer
        string defaultUserName = this._configuration["UserSettings:DefaultUser:Name"];
        //loading int value
        int defaultUserAge = this._configuration.GetValue<int>("UserSettings:DefaultUser:Age");

        return View((isDemoMode, defaultUserName, defaultUserAge));
    }

    ...
}

Acquisition of configuration information with option patterns

As I mentioned in the previous article, it’s better to bind the configuration information to a class and get it from there for better readability.

Define a class that corresponds to the JSON definition.
As I explained last time, add a class file from Visual Studio, copy the string of the JSON file, and select [Edit]-[Paste Select Format]-[Paste JSON as Class]. Then you can paste the class definition, which is convenient.

UserSettings.cs



    public class UserSettings
    {
        public bool IsDemoMode { get; set; }
        public DefaultUser DefaultUser { get; set; }
    }

    public class DefaultUser
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }

Then inject configuration information from StartUp.ConfigureServices through the service collection.

Startup.cs



public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        //Injection of configuration information
        services.Configure<UserSettings>(this.Configuration.GetSection("UserSettings"));
        services.AddControllersWithViews();            
    }

    ...
}

You can now get the injected configuration information from the controller.

HomeController.cs



public class HomeController : Controller
{
    private readonly UserSettings _userSettings;

    private readonly ILogger<HomeController> _logger;        

    public HomeController(IOptions<UserSettings> userSettings, ILogger<HomeController> logger)
    {
        //Get configuration information
        this._userSettings = userSettings.Value;
        this._logger = logger;
    }

    public IActionResult Index()
    {
        //Reference of configuration information
        return View(this._userSettings);
    }

    ...
}

It’s still more readable if you get the configuration information via a unique class.

Reference site