Skip to content

Strongly typed configuration

appsettings.json

appsettings can be used to store configuration values like database connection string, api urls, keys, secrets, settings like feature toggle, log level etc.

Values in appsettings.json will be overwritten by values in appsettings.Development.json. Both of them are often committed to the code. For other environments like staging, uat and beta, there can be appsettings.staging.json etc and these are not committed to the code.

The default appsettings.Development.json has a nested logging configuration

json
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  }
}

We can get Logging.LogLevel.Default's value using

csharp
var logLevelDefault = builder.Configuration["Logging:LogLevel:Default"];

Log.Information("Log level default {logLevelDefault}", logLevelDefault);

This works but there might be code like configuration["Setting:PageSize"] at multiple places and changing appsettings would mean changing all those code.

Appsettings class

A better approach is using classes to get these values.

First, add a folder Utilities and add a class AppSettings.cs.

csharp
public class AppSettings
{
    public string Timezone { get; set; }
}

In appsettings.Development.json, add Timezone

Now, to get config we use

csharp
configuration.Get<AppSettings>().Timezone;

Back in WeatherForecastController, we can inject IConfiguration

csharp
var timezone = config.Get<AppSettings>().Timezone;
        logger.LogInformation("WeatherForecastController.Index - Timezone {timezone}", timezone);

Released under the MIT License.