You should use Dependency Injection and the .NET Configuration system:
- Inject
IConfiguration
, and store the instance in a member/variable likeConfiguration
- Add the
using Microsoft.Extensions.Configuration
statement - Read the app settings like this:
var intervals = Configuration.GetSection("TimeInterval").Get<List<TimeInterval>>();
You can also use options pattern to get the settings. But to avoid a long post, I'll just share two examples on how to get configs in the page or in a page model. Fore more information, take a look at links at the bottom of the post.
Example 1 - Getting configuration in a Blazor Page
Assuming you have the following class:
public class TimeInterval
{
public string Title { get; set; }
public int Hours { get; set; }
}
Then in a page, you can inject IConfiguration
and read the settings:
@page "/"
@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration
<h1>Hello, world!</h1>
<ul>
@{
var intervals = Configuration.GetSection("TimeInterval").Get<List<TimeInterval>>();
foreach (var item in intervals)
{
<li>@item.Title: @item.Hours Hours</li>
}
}
</ul>
Welcome to your new app.
Example 2 - Getting configuration in a PageModel class:
Inject the IConfiguration
and read settings like this:
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Configuration;
using System.Collections.Generic;
namespace WebApplication1.Pages
{
public class IndexModel : PageModel
{
public IConfiguration Configuration;
public IndexModel(IConfiguration configuration)
{
Configuration = configuration;
}
public void OnGet()
{
var intervals = Configuration.GetSection("TimeInterval").Get<List<TimeInterval>>();
}
}
}
More information: