
Customizing ASP.NET Core 6.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:
namespace ConfigureSample; public class AppSettings { public int Foo { get; set; } public string Bar { get; set; } }
This is a simple Plain Old CLR Object (POCO) class that will only contain the application setting values, as illustrated in the following code snippet. These classes can then be filled with specific configuration sections inside the ConfigureServices
method in Startup.cs
until ASP.NET Core 5.0:
services.Configure<AppSettings> (Configuration.GetSection("AppSettings"));
Using the minimal API approach, you need to configure the AppSettings
class, like this:
builder.Services.Configure<AppSettings>( builder.Configuration.GetSection("AppSettings"));
This way, the typed configuration also gets registered as a service in the dependency injection (DI) 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:
using Microsoft.Extensions.Options; // ... public class HomeController : Controller { private readonly AppSettings _options; public HomeController(IOptions<AppSettings> options) { _options = options.Value; } public IActionResult Index() { ViewData["Message"] = _options.Bar; return View(); }
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 reading the settings in, 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 the appsettings.json
file, as follows:
{ "Logging": { "LogLevel": { "Default": "Warning" } }, "AllowedHosts": "*", "AppSettings": { "Foo": 123, "Bar": "Bar" } }
Next, we'll examine how INI files can be used for configuration.