Full stack dev🧑🏻‍💻

How to read appSettings in .NET Core with a typed model

Posted

Last updated

2 min read

Cover Image for How to read appSettings in .NET Core with a typed model

So, you're developing something and deciding to put some settings in appSettings instead of hard coding it? But how do you read those settings in your code in a nice way?

As with most things in development, you can solve this using multiple different techniques. My own preferred way is by using a C# model that we then bind our config to so that the hardly typed model can be used to access the different properties / settings by simply injecting it wherever it is desired to be used.

TL;DR, just get the sample repository here yourself: https://github.com/fullstackdev-cloud/appSettingsSample/tree/main

1. Create a new .NET Core project

If you don't already have a project set up, simply create one using Visual Studio or just run the command to create a project such as: dotnet new -webapi.

This creates a new web api project, and we'll use it to demonstrate the reading of appSettings.json. Let's keep everything in the project just for the sake of it so we can do a simple test of our appSettings connection.

2. Add a new section in appSettings.json

Add new properties in the appSettings.json file so we can demonstrate reading the value. Below is an example of the section I added for this test, see "AppConfig" on lines 9 to 13. Your appSettings.json should look something like this:

1{
2  "Logging": {
3    "LogLevel": {
4      "Default": "Information",
5      "Microsoft.AspNetCore": "Warning"
6    }
7  },
8  "AllowedHosts": "*",
9  "AppConfig": {
10    "AppName": "TestApp",
11    "AppVersion": "1.0.0",
12    "AppEnvironment": "DEV"
13  }
14}
15

3. Create a C# model to bind your setting to it

Just add a new file with a property that will hold the value from appSettings.json, see:

1namespace appSettingsSample
2{
3    public class AppConfig
4    {
5        public string AppName { get; set; }
6        public string AppVersion { get; set; }
7        public string AppEnvironment { get; set; }
8    }
9}
10

4. Bind your model to the appSetting setting

Go to the Program.cs file and add a line to connect the model to the setting, and make sure you add it before the builder.Build() method is run, see line 9.

Your Program.cs file should look like this:

1using appSettingsSample;
2
3var builder = WebApplication.CreateBuilder(args);
4builder.Services.AddControllers();
5builder.Services.AddEndpointsApiExplorer();
6builder.Services.AddSwaggerGen();
7
8// Bind the config to our AppConfig class.
9builder.Services.Configure<AppConfig>(builder.Configuration.GetSection("AppConfig"));
10
11var app = builder.Build();
12
13// Configure the HTTP request pipeline.
14if (app.Environment.IsDevelopment())
15{
16    app.UseSwagger();
17    app.UseSwaggerUI();
18}
19
20app.UseHttpsRedirection();
21
22app.UseAuthorization();
23
24app.MapControllers();
25
26app.Run();
27

That's it for the setup, now we should be able to simply inject the settings model and use it wherever we want.

5. Inject the model and read the appSettings config value anywhere

Let's say you want to use a config value inside your controller, you can simply access it by injecting it in the constructor. Let's use the WeatherForecastController that was added by the template when we ran dotnet new webapi.

Look at the constructor which is where we're injecting it, and then we can simply get the values from the model as displayed in the Get method, see the row where info is logged in the Get() method, see line 23:

1using Microsoft.AspNetCore.Mvc;
2using Microsoft.Extensions.Options;
3
4namespace appSettingsSample.Controllers;
5
6[ApiController]
7[Route("[controller]")]
8public class WeatherForecastController : ControllerBase
9{
10    private readonly ILogger<WeatherForecastController> _logger;
11    private readonly IOptions<AppConfig> _appConfiguration;
12
13    public WeatherForecastController(ILogger<WeatherForecastController> logger, IOptions<AppConfig> appConfiguration)
14    {
15        _logger = logger;
16        _appConfiguration = appConfiguration;
17    }
18
19    [HttpGet(Name = "GetWeatherForecast")]
20    public IEnumerable<WeatherForecast> Get()
21    {
22        // Log the appConfig values to see what we're getting from appSettings.json
23        _logger.LogInformation($"Environment: {_appConfiguration.Value.AppEnvironment}, Version: {_appConfiguration.Value.AppVersion}, Name: {_appConfiguration.Value.AppName}");
24        
25        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
26        {
27            Date = DateTime.Now.AddDays(index),
28            TemperatureC = Random.Shared.Next(-20, 55),
29        })
30        .ToArray();
31    }
32}
33

Isa
Isa

More Stories

Cover Image for C# Cosmos DB simple "lock" functionality by implementing Optimistic Concurrency Control

C# Cosmos DB simple "lock" functionality by implementing Optimistic Concurrency Control

Prevent data corruption when multiple users concurrently try to update a single Cosmos DB item in an Azure Function. Implement optimistic concurrency control using ETags and retry logic to ensure correct updates....

Cover Image for Exploring the Power of Kusto Query Language in Azure Application Insights

Exploring the Power of Kusto Query Language in Azure Application Insights

In this blog post we will look into a few samples of Kusto queries. The purpose of this is to get familiar with how queries look like and how they can be tested out in the Azure portal....