Asp.Net Core Reading Configuration Values Complete Guide

 Last Update:2025-06-23T00:00:00     .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    7 mins read      Difficulty-Level: beginner

Understanding the Core Concepts of ASP.NET Core Reading Configuration Values

ASP.NET Core Reading Configuration Values: A Detailed Explanation with Important Info

Configuration Providers

Configuration providers in ASP.NET Core are responsible for providing configuration values from various sources:

  1. File-based Providers

    • JSON Configuration Provider:

      • Stores configurations in JSON files.
      • Typically used for appsettings.json.
      • Supports hierarchical keys using colon (:) or double underscore (__) conventions.
      • Example usage in Program.cs:
        var builder = WebApplication.CreateBuilder(args);
        builder.Configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
        
    • XML Configuration Provider:

      • Utilizes XML files for configuration.
      • Useful when transitioning projects from earlier versions of ASP.NET where XML was traditionally used.
      • Adds complexity due to the verbosity of XML.
      • Example:
        builder.Configuration.AddXmlFile("config.xml", optional: false, reloadOnChange: true);
        
    • INI Configuration Provider:

      • Supports INI files, a simple format that was common in early Windows application settings.
      • Generally less used today in favor of more modern formats like JSON.
      • Example:
        builder.Configuration.AddIniFile("config.ini", optional: true, reloadOnChange: true);
        
  2. Environment Variables Provider:

    • Allows reading configuration from environment variables at runtime.
    • Ideal for secrets (e.g., API keys) and settings that should not be hardcoded into configuration files.
    • Environment variable names are typically in uppercase with double underscores (__) separating nested keys.
    • Example:
      builder.Configuration.AddEnvironmentVariables();
      
  3. Command-line Arguments Provider:

    • Enables configuration via command-line arguments during application startup.
    • Commonly used for passing dynamic settings or overriding other configurations.
    • Command-line argument names follow the --key:value convention.
    • Example:
      builder.Configuration.AddCommandLine(args);
      
  4. Memory Configuration Provider:

    • Used to provide in-memory settings programmatically.
    • Often useful for testing scenarios or when you need to set default values.
    • Can be initialized with a dictionary of key-value pairs.
    • Example:
      builder.Configuration.AddInMemoryCollection(new Dictionary<string, string>
      {
          { "Key", "Value" },
          { "Section:Key", "Section Value" }
      });
      
  5. Custom Providers:

    • Developers can create custom configuration providers to integrate with other data stores.
    • Useful when existing providers do not meet your requirements.
    • Custom providers derive from the abstract ConfigurationProvider class.

Hierarchical Keys and Access Patterns

  • Delimiter Format: Use colons (:) for separating nested keys in hierarchical configurations.

    • For example, the following JSON configuration:
      {
        "Logging": {
          "LogLevel": {
            "Default": "Information",
            "Microsoft.AspNetCore": "Warning"
          }
        }
      }
      
    • Can be accessed in code as follows:
      var LogLevelDefault = builder.Configuration["Logging:LogLevel:Default"];
      var LogLevelMicrosoftAspNetCore = builder.Configuration["Logging:LogLevel:Microsoft.AspNetCore"];
      
  • Double Underscore Format: As an alternative to colons, use double underscores (__) to specify hierarchical keys.

    • This is particularly useful when configuring settings through environment variables.
    • Example:
      Logging__LogLevel__Default
      

Bindings and Options Pattern

  • Binding Configuration: Configuration sections can be bound directly to properties on classes using Bind.

    • This helps in organizing configuration into logical groups represented by objects.
    • Example:
      public class MySettings
      {
          public string KeyOne { get; set; }
          public int KeyTwo { get; set; }
      }
      
      var mySettings = new MySettings();
      builder.Configuration.GetSection("MySettings").Bind(mySettings);
      
  • Options Pattern: Simplifies and enhances configuration management by using IOption<T> or IOptionsMonitor<T>.

    • Options pattern promotes loose coupling between configuration and classes that depend on it.
    • Example:
      • Define a settings class:
        public class MySettings
        {
            public string KeyOne { get; set; }
            public int KeyTwo { get; set; }
        }
        
      • Register and bind the settings in ConfigureServices:
        services.Configure<MySettings>(builder.Configuration.GetSection("MySettings"));
        
      • Inject the options as a service in your controllers:
        private readonly IOptionsSnapshot<MySettings> _options;
        
        public HomeController(IOptionsSnapshot<MySettings> options)
        {
            _options = options;
        }
        
        public IActionResult Index()
        {
            return Content($"KeyOne: {_options.Value.KeyOne}, KeyTwo: {_options.Value.KeyTwo}");
        }
        

Built-in Framework Settings

ASP.NET Core reads several built-in settings from appsettings.json or other configuration providers automatically:

  • Connection Strings: Stored in ConnectionStrings section.

    • Can be accessed via IConfiguration.GetConnectionString(string name).
    • Example appsettings.json:
      {
        "ConnectionStrings": {
          "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=TestDb;Trusted_Connection=True;"
        }
      }
      
    • Example access in C#:
      options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
      
  • Logging Configurations: Defined under Logging section.

    • Configure loggers, levels, providers, etc.
    • Example appsettings.json:
      {
        "Logging": {
          "LogLevel": {
            "Default": "Information",
            "Microsoft.AspNetCore": "Warning"
          }
        }
      }
      
  • Application-Specific Settings: Developers can place custom settings under any desired section.

    • Best practice is to use clear, meaningful section names corresponding to their purpose.

Best Practices

  • Configuration Precedence: Understand the order in which configuration providers are registered; later providers override previous ones.
  • Optional and Reloadable Configurations: Always mark configuration files as optional if they might not exist, handle missing files gracefully.
  • Environment-Specific Configurations: Use appsettings.{Environment}.json (like appsettings.Development.json, appsettings.Production.json) for setting specific to different deployment environments.
  • Security Considerations: Avoid storing sensitive information like passwords or API keys in plain text configuration files.
  • Use Options Pattern: Leverage the options pattern to keep configuration separate from business logic, making code cleaner and easier to maintain.

Online Code run

🔔 Note: Select your programming language to check or run code at

💻 Run Code Compiler

Step-by-Step Guide: How to Implement ASP.NET Core Reading Configuration Values

Step 1: Create a New ASP.NET Core Project

First, let's create a new ASP.NET Core Web Application. You can do this using the .NET CLI or Visual Studio.

Using .NET CLI

dotnet new web -n ConfigDemoApp
cd ConfigDemoApp
dotnet build

Using Visual Studio

  1. Open Visual Studio.
  2. Select "Create a new project".
  3. Choose "ASP.NET Core Web App" and click "Next".
  4. Enter the project name "ConfigDemoApp" and click "Create".
  5. Choose ".NET Core" and "ASP.NET Core 5.0" (or later) and click "Create".

Step 2: Add Configuration Values to appsettings.json

The appsettings.json file is used to store configuration data for your application. You can add various settings here.

Open appsettings.json in your root folder and add some configuration values:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "AppSettings": {
    "ApplicationName": "ConfigDemoApp",
    "Version": "1.0.0",
    "ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=DemoDb;Trusted_Connection=True;"
  }
}

Step 3: Bind Configuration Values to a C# Class

To make accessing these settings easier, you can bind them to a C# class. Create a new class named AppSettings:

// AppSettings.cs
public class AppSettings
{
    public string ApplicationName { get; set; }
    public string Version { get; set; }
    public string ConnectionString { get; set; }
}

Step 4: Configure Services to Use Configuration

In the Startup.cs file (or Program.cs if you are using .NET 6 or later), configure the services to use the configuration settings. For .NET 6, this is typically done in Program.cs.

For .NET 6 (Program.cs)

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

// Configure configuration
builder.Configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);

// Bind configuration to AppSettings class
builder.Services.Configure<AppSettings>(builder.Configuration.GetSection("AppSettings"));

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

For .NET Core 5 (Startup.cs)

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();

        // Bind configuration to AppSettings class
        services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

Step 5: Access Configuration Values in a Controller

Now, you can access these configuration values in any controller by using IOptions<T>.

Create a new controller HomeController and inject IOptions<AppSettings>:

// HomeController.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;

public class HomeController : Controller
{
    private readonly AppSettings _appSettings;

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

    public IActionResult Index()
    {
        ViewBag.ApplicationName = _appSettings.ApplicationName;
        ViewBag.Version = _appSettings.Version;
        ViewBag.ConnectionString = _appSettings.ConnectionString;
        return View();
    }
}

Step 6: Display Configuration Values in a View

Finally, display these values in your Index.cshtml view:

@{
    ViewData["Title"] = "Home Page";
}

<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <p>Application Name: @ViewBag.ApplicationName</p>
    <p>Version: @ViewBag.Version</p>
    <p>Connection String: @ViewBag.ConnectionString</p>
</div>

Step 7: Run Your Application

Run your application using the .NET CLI or Visual Studio.

dotnet run

Navigate to the home page, and you should see the configuration values displayed:

Top 10 Interview Questions & Answers on ASP.NET Core Reading Configuration Values

1. What are Configuration Values in ASP.NET Core?

  • Answer: Configuration values in ASP.NET Core are settings that can be changed to alter the behavior of an application without editing the code. These values can come from various sources like app settings files, environment variables, command-line arguments, and more.

2. How do you read configuration values from appsettings.json in ASP.NET Core?

  • Answer: You can read configuration values from the appsettings.json by using the IConfiguration interface. In ASP.NET Core applications, this is usually automatically set up during application startup and can be added to your controllers or other services by dependency injection.
public class Startup
{
    public IConfiguration Configuration { get; }

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }
}

public class MyController : Controller
{
    private readonly IConfiguration _configuration;

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

    public IActionResult Index()
    {
        var myConfigValue = _configuration["MyConfigKey"];
        return View();
    }
}

3. Can I bind configuration values to POCO classes in ASP.NET Core?

  • Answer: Yes, you can bind configuration values to Plain Old CLR Objects (POCO classes) using the GetSection method followed by Bind(). This allows you to keep your configuration structure organized and easy to maintain.
public class MyOptions
{
    public string MyConfigKey { get; set; }
    public int MyIntConfig { get; set; }
}

public class SomeService
{
    private readonly MyOptions _options;

    public SomeService(IConfiguration configuration)
    {
        _options = new MyOptions();
        configuration.GetSection("MyOptions").Bind(_options);
    }
}

4. How do you override configuration values with environment variables in ASP.NET Core?

  • Answer: Environment variables take precedence over values set in the appsettings.json file. You can override settings by setting an environment variable with the same key name as the configuration setting.
// In appsettings.json
{
    "MyConfigKey": "Value from appsettings.json"
}

// In .NET code with Dependency Injection
var myConfigValue = _configuration["MyConfigKey"];

If you set an environment variable MyConfigKey to Value from Environment Variable, then myConfigValue will be Value from Environment Variable.

5. What is the recommended way to use configuration in ASP.NET Core?

  • Answer: The recommended way is to use the IConfiguration interface along with a POCO class for options. This allows for type safety and better maintainability.

You May Like This Related .NET Topic

Login to post a comment.