.NET  

How to Read appsettings.json Values in .NET 8 Correctly?

Introduction

In modern application development, especially when working with ASP.NET Core and .NET 8 Web API, managing configuration properly is very important. Applications often need to store values like database connection strings, API keys, feature flags, and application-level settings.

Instead of hardcoding these values in code (which is a bad practice), .NET provides a clean and flexible way to manage them using appsettings.json in .NET 8.

What is appsettings.json in .NET 8?

The appsettings.json file in ASP.NET Core is a configuration file where you store application settings in a structured JSON format.

It acts like a central storage for all your configuration values.

Example of appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "ConnectionStrings": {
    "DefaultConnection": "Server=.;Database=MyDb;Trusted_Connection=True;"
  },
  "AppSettings": {
    "AppName": "MyApp",
    "Version": "1.0"
  }
}

πŸ‘‰ Here you can see:

  • Logging configuration

  • Database connection string

  • Custom application settings

Why Use appsettings.json in .NET 8 Web API?

Using appsettings.json in .NET 8 Web API gives many advantages.

1. Centralized Configuration

All your important settings are stored in one place.

πŸ‘‰ Example:
Instead of searching values in different files, you can find everything inside appsettings.json.

This makes your application easier to manage and maintain.

2. Easy to Update Without Code Changes

You don’t need to modify code when configuration changes.

πŸ‘‰ Example:
If your database connection string changes, you just update appsettings.json.

No need to re-write logic.

3. Environment-Based Configuration

.NET supports multiple environments like:

  • Development

  • Staging

  • Production

You can create files like:

  • appsettings.Development.json

  • appsettings.Production.json

πŸ‘‰ This helps you keep different values for different environments.

4. Secure and Scalable Configuration

You can combine appsettings.json with:

  • Environment variables

  • Secret Manager

  • Cloud services (like Azure Key Vault)

This ensures security and scalability in real-world applications.

Ways to Read appsettings.json Values in .NET 8

Let’s now understand different ways to read configuration values.

Method 1: Using IConfiguration (Basic and Direct Approach)

This is the simplest and most commonly used method.

Step 1: Inject IConfiguration

private readonly IConfiguration _configuration;

public HomeController(IConfiguration configuration)
{
    _configuration = configuration;
}

πŸ‘‰ Here, .NET automatically injects IConfiguration using Dependency Injection.

Step 2: Read Values

var appName = _configuration["AppSettings:AppName"];
var version = _configuration["AppSettings:Version"];

Explanation

  • "AppSettings" is the section

  • "AppName" is the key inside that section

  • Colon (:) is used to access nested values

πŸ‘‰ This approach is simple but uses "magic strings", which can lead to errors if names are incorrect.

Method 2: Using GetSection() for Better Readability

When you need multiple values from the same section, this method is cleaner.

var section = _configuration.GetSection("AppSettings");
var appName = section["AppName"];
var version = section["Version"];

Why Use This?

  • Improves readability

  • Avoids repeating long keys

πŸ‘‰ Useful when working with grouped configuration values.

Method 3: Strongly Typed Configuration (Best Practice)

This is the most recommended approach in .NET 8 configuration management.

Step 1: Create a Class

public class AppSettings
{
    public string AppName { get; set; }
    public string Version { get; set; }
}

πŸ‘‰ This class represents your configuration structure.

Step 2: Register in Program.cs

builder.Services.Configure<AppSettings>(
    builder.Configuration.GetSection("AppSettings"));

Step 3: Inject IOptions

private readonly AppSettings _appSettings;

public HomeController(IOptions<AppSettings> options)
{
    _appSettings = options.Value;
}

Step 4: Use Values

var appName = _appSettings.AppName;

Why This is Best Practice?

  • Type-safe (no string errors)

  • IntelliSense support

  • Clean and maintainable code

  • Easy to scale in large projects

πŸ‘‰ This approach is widely used in enterprise-level .NET applications.

Method 4: Using IOptionsSnapshot (Scoped Configuration)

This is useful when configuration values may change per request.

public HomeController(IOptionsSnapshot<AppSettings> options)
{
    var appName = options.Value.AppName;
}

When to Use?

  • Web applications

  • When values can change between requests

πŸ‘‰ It reloads configuration for every request.

Method 5: Using IOptionsMonitor (Real-Time Updates)

public HomeController(IOptionsMonitor<AppSettings> options)
{
    var appName = options.CurrentValue.AppName;
}

When to Use?

  • Background services

  • Real-time configuration updates

πŸ‘‰ Automatically updates values when appsettings.json changes.

Reading Connection Strings in .NET 8

.NET provides a built-in method for connection strings.

var connectionString = _configuration.GetConnectionString("DefaultConnection");

Why Use This?

  • Cleaner code

  • Standard practice

  • Avoids manual string parsing

πŸ‘‰ Always prefer this method for database connections.

Using appsettings.json in Minimal APIs (.NET 8)

Minimal APIs are very popular in .NET 8.

var builder = WebApplication.CreateBuilder(args);

var appName = builder.Configuration["AppSettings:AppName"];

var app = builder.Build();

Why This is Useful?

  • Simple and clean

  • Less boilerplate code

  • Faster development

πŸ‘‰ Best for lightweight APIs and microservices.

Environment-Based Configuration in .NET 8

.NET automatically loads multiple configuration files.

Order of Loading

  1. appsettings.json

  2. appsettings.{Environment}.json

  3. Environment variables

Example

ASPNETCORE_ENVIRONMENT=Development

πŸ‘‰ This allows different values for development and production.

Best Practices for Reading Configuration in .NET 8

1. Use Strongly Typed Configuration

Avoid using string keys everywhere.

πŸ‘‰ Makes code clean and error-free.

2. Avoid Hardcoding Values

Never write values directly in code.

πŸ‘‰ Always use configuration files.

3. Secure Sensitive Data

Do not store:

  • Passwords

  • API keys

πŸ‘‰ Use Secret Manager or environment variables.

4. Validate Configuration Values

Always ensure required values exist.

πŸ‘‰ Prevents runtime errors.

5. Use Environment Variables in Production

More secure and flexible approach for deployment.

Common Mistakes to Avoid

  • ❌ Using too many magic strings

  • ❌ Not using strongly typed configuration

  • ❌ Storing sensitive data in appsettings.json

  • ❌ Ignoring environment-specific settings

Real-World Example

In a real-world ASP.NET Core Web API application, you might store:

  • Database connection strings

  • Third-party API keys

  • Application settings

Using appsettings.json in .NET 8 helps manage all these values efficiently and cleanly.

Summary

Reading appsettings.json values in .NET 8 correctly is essential for building scalable, secure, and maintainable applications. While IConfiguration provides a quick and simple way to access values, strongly typed configuration using IOptions is the recommended approach for clean and production-ready code. By following best practices like environment-based configuration, secure handling of sensitive data, and proper validation, you can build high-quality .NET 8 applications that are flexible, efficient, and easy to maintain.