
Customizing ASP.NET Core 5.0
By :

Before trying to read INI files, it makes sense for you to see how to use typed configurations instead of reading the configuration via IConfiguration
, key by key.
To read a typed configuration, you need to define the type to configure. I usually create a class called AppSettings
, as follows:
public class AppSettings { public int Foo { get; set; } public string Bar { get; set; } }
This is a simple POCO class that will only contain the application setting values. These classes can then be filled with specific configuration sections inside the ConfigureServices
method in Startup.cs
:
services.Configure<AppSettings> (Configuration.GetSection("AppSettings"));
This way, the typed configuration also gets registered as a service in the dependency injection container and can be used everywhere in the application. You are able to create different configuration types for each configuration section. In most cases, one section should be fine, but sometimes it makes sense to divide the settings into different sections. The next snippet shows how to use the configuration in an MVC controller:
public class HomeController : Controller { private readonly AppSettings _options; public HomeController(IOptions<AppSettings> options) { _options = options.Value; }
IOptions<AppSettings>
is a wrapper around our AppSettings
type, and the Value
property contains the actual instance of AppSettings
, including the values from the configuration file.
To try that, the appsettings.json
file needs to have the AppSettings
section configured, otherwise the values are null or not set. Let's now add the section to appsettings.json
:
{ "Logging": { "LogLevel": { "Default": "Warning" } }, "AllowedHosts": "*", "AppSettings": { "Foo": 123, "Bar": "Bar" } }
Next, we'll examine how INI files can be used for configuration.