Asp.Net Core Configuration Sources Appsettings Json Environment Variables 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 Configuration Sources appsettings json, Environment Variables

Understanding ASP.NET Core Configuration

ASP.NET Core introduces a new and flexible configuration system that allows you to load settings from various providers. This system is designed to be modular, making it easy to add new providers based on your needs. The core interface for accessing the configuration is IConfiguration.

appsettings.json Configuration Source

What is appsettings.json?

  • Structure: appsettings.json is a JSON file located in the root of an ASP.NET Core project.
  • Purpose: This file is primarily used to store application-wide settings that can be changed without recompiling the application.
  • Usage: Typically, appsettings.json is used for settings like connection strings, logging levels, and other configuration values that are consistent across different stages of the application's lifecycle.

Example Structure

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning",
      "System": "Error",
      "Microsoft": "Error"
    }
  },
  "AllowedHosts": "*"
}

How to Access appsettings.json Settings

ASP.NET Core projects configure the IConfiguration object in the Program.cs file using Host.CreateDefaultBuilder().

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

The CreateDefaultBuilder method, among other things, sets up the configuration system by default, including:

  • appsettings.json
  • appsettings.{Environment}.json (where {Environment} is your app's environment, for example, appsettings.Development.json)
  • Command-line arguments
  • Environment variables

Accessing the configuration values is straightforward using dependency injection.

public class MyController : ControllerBase
{
    private readonly IConfiguration _configuration;

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

    [HttpGet]
    public string GetConnectionString()
    {
        return _configuration.GetConnectionString("DefaultConnection");
    }
}

Environment Variables Configuration Source

What are Environment Variables?

  • Purpose: Environment variables are name-value pairs stored outside the application's code or data files, but accessible to the application via the system or runtime environment.
  • Usage: They are commonly used to store sensitive information such as API keys, database connection strings, or other secrets that should not be hardcoded into the application.

How to Set Environment Variables

  • Windows: Use the System Properties or PowerShell.

    [System.Environment]::SetEnvironmentVariable("ConnectionStrings__DefaultConnection", "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;", [System.EnvironmentVariableTarget]::Machine)
    
  • Linux/macOS: Use the export command in the terminal.

    export ConnectionStrings__DefaultConnection="Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;"
    

Loading Environment Variables in ASP.NET Core

By default, the CreateDefaultBuilder method used in Program.cs also loads environment variables. You can access these just like settings from appsettings.json.

public class MyController : ControllerBase
{
    private readonly IConfiguration _configuration;

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

    [HttpGet]
    public IActionResult GetEnvironmentVariable()
    {
        var envVar = _configuration["AnyEnvironmentVariableName"];
        return Ok(new { envVar });
    }
}

Hierarchical Configuration

One of the powerful features of ASP.NET Core's configuration system is its support for hierarchical settings. You can reference nested properties using the colon (:) separator (or double underscore __ in environment variables).

For example, to access the logging level for Microsoft:

string logLevel = _configuration["Logging:LogLevel:Microsoft"];

Or, in an environment variable:

export Logging__LogLevel__Microsoft=Error

Configuration Binding

Configuration values can be bound to strongly-typed objects using the IConfiguration interface.

public class AppSettings
{
    public ConnectionStrings ConnectionStrings { get; set; }

    public class ConnectionStrings
    {
        public string DefaultConnection { get; set; }
    }
}

Binding to an object:

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 Configuration Sources appsettings json, Environment Variables

Step 1: Create a New ASP.NET Core Project

You can create a new ASP.NET Core project using the .NET CLI or Visual Studio.

Using .NET CLI

Open your terminal and run the following command:

dotnet new webapp -o MyApp
cd MyApp

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 MyApp and click "Next".
  5. Select ".NET 6.0 (Long-term support)" or the latest version, and click "Create".

Step 2: Understand Configuration in ASP.NET Core

ASP.NET Core uses an IConfiguration object that represents the configuration key-value pairs. This IConfiguration object is populated by configuration providers like appsettings.json and environment variables.

Step 3: Use appsettings.json for Configuration

  1. Open the appsettings.json file in your project. By default, it should look like this:

    {
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft.AspNetCore": "Warning"
        }
      },
      "AllowedHosts": "*"
    }
    
  2. Add some custom settings to this file. For example:

    {
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft.AspNetCore": "Warning"
        }
      },
      "AllowedHosts": "*",
      "MySettings": {
        "Setting1": "Value1",
        "Setting2": 42
      }
    }
    

Step 4: Accessing Configuration in Code

Inject the IConfiguration object into your controllers or services to access these settings.

  1. Open Controllers/HomeController.cs and modify it to read the MySettings configuration.

    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Configuration;
    
    namespace MyApp.Controllers
    {
        public class HomeController : Controller
        {
            private readonly IConfiguration _configuration;
    
            public HomeController(IConfiguration configuration)
            {
                _configuration = configuration;
            }
    
            public IActionResult Index()
            {
                var setting1 = _configuration.GetValue<string>("MySettings:Setting1");
                var setting2 = _configuration.GetValue<int>("MySettings:Setting2");
    
                ViewBag.Setting1 = setting1;
                ViewBag.Setting2 = setting2;
    
                return View();
            }
    
            // Other actions...
        }
    }
    
  2. Update the Views/Home/Index.cshtml file to display these settings.

    @using Microsoft.AspNetCore.Mvc.RazorPages
    @model IndexModel
    @{
        ViewData["Title"] = "Home page";
    }
    
    <div class="text-center">
        <h1 class="display-4">Welcome</h1>
        <p>Setting1: @ViewBag.Setting1</p>
        <p>Setting2: @ViewBag.Setting2</p>
    </div>
    

Step 5: Use Environment Variables for Configuration

Environment variables are useful for secrets and environment-specific settings. To use them, follow these steps:

  1. Set an environment variable. The name of the environment variable should match the configuration key, but with double underscores (__) instead of colons.

    • For Windows (Command Prompt):

      setx MySettings__Setting1 "EnvironmentValue1"
      
    • For macOS/Linux (Terminal):

      export MySettings__Setting1="EnvironmentValue1"
      
  2. Modify Program.cs to add environment variables as a configuration source. By default, ASP.NET Core already includes environment variables, but you can ensure it’s included by calling AddEnvironmentVariables.

    var builder = WebApplication.CreateBuilder(args);
    
    // Add configuration from appsettings.json and environment variables
    builder.Configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                         .AddEnvironmentVariables();
    
    var app = builder.Build();
    
    // Other configurations and app settings...
    
  3. Run the application and observe that the environment variable overrides the appsettings.json value for MySettings:Setting1.

Step 6: Verify the Configuration

  1. Run the application.

    • Using .NET CLI:
      dotnet run
      
    • In Visual Studio, press Ctrl+F5 or F5.
  2. Navigate to the home page (http://localhost:5000).

  3. You should see the values for Setting1 and Setting2 displayed on the page. If you have set an environment variable for MySettings__Setting1, it should override the value in appsettings.json.

Conclusion

Top 10 Interview Questions & Answers on ASP.NET Core Configuration Sources appsettings json, Environment Variables

Top 10 Questions and Answers on ASP.NET Core Configuration Sources: appsettings.json and Environment Variables

Q1: What is the purpose of appsettings.json in an ASP.NET Core application?

Q2: How can I use appsettings.json to manage multiple environments (development, staging, production)?

A2: ASP.NET Core allows you to manage environment-specific settings by creating additional configuration files named appsettings.{Environment}.json (e.g., appsettings.Development.json or appsettings.Staging.json). The application will automatically load the settings from the appropriate file based on the current hosting environment specified by the ASPNETCORE_ENVIRONMENT environment variable. Settings in these files will override those in the base appsettings.json file.

Q3: Can you explain how the Environment Variables are used in ASP.NET Core configuration?

A3: Environment variables are used in ASP.NET Core to provide configuration values that are meant to be set outside the application. This is particularly useful for sensitive data like API keys, secrets, and database connection strings. Environment variables can be easily integrated into the application's configuration system, and they take precedence over the settings in JSON configuration files, allowing for configuration values to be dynamically changed without redeploying the application.

Q4: What is the order of precedence when resolving configuration values in ASP.NET Core?

A4: In ASP.NET Core, the configuration system loads settings from multiple sources, including files (appsettings.json, appsettings.{Environment}.json), environment variables, command-line arguments, and more. The order of precedence, from lowest to highest, is:

  1. appsettings.json
  2. appsettings.{Environment}.json
  3. User secrets (development only)
  4. Environment variables
  5. Command-line arguments

This means that if the same configuration key is defined in multiple sources, the value from the source with the highest precedence will be used by the application.

Q5: How can I read configuration values from appsettings.json and Environment Variables in ASP.NET Core?

A5: Configuration values in ASP.NET Core can be read using the IConfiguration interface, which is configured in the Program.cs or Startup.cs file. Here’s an example of how you might access a string setting from appsettings.json and an environment variable:

public class Startup
{
    private readonly IConfiguration _configuration;

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

    public void ConfigureServices(IServiceCollection services)
    {
        // Accessing a value from appsettings.json
        var myAppSetting = _configuration["MyAppSettingKey"];

        // Accessing a value from an environment variable
        var myEnvVariable = _configuration["MY_ENV_VAR"];
        // Note: By convention, environment variables are typically in all uppercase letters.

        services.AddTransient<IMyService>(sp => new MyService(myAppSetting, myEnvVariable));
    }

    // ...
}

Q6: How can I bind configuration sections to classes in ASP.NET Core?

A6: Binding a configuration section to a class is a powerful way to organize and access complex configuration data. You can define a configuration class that matches the structure of your JSON settings and use the IConfiguration methods to bind the section:

public class MyConfig
{
    public string Setting1 { get; set; }
    public int Setting2 { get; set; }
}

public class Startup
{
    private readonly IConfiguration _configuration;

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

    public void ConfigureServices(IServiceCollection services)
    {
        var myConfig = new MyConfig();
        _configuration.GetSection("MyConfig").Bind(myConfig);

        services.AddSingleton(myConfig);
        // Now MyConfig is available as a singleton service.
    }

    // ...
}

And in appsettings.json:

{
  "MyConfig": {
    "Setting1": "Value1",
    "Setting2": 42
  }
}

Q7: How can I use configuration providers other than JSON and environment variables in ASP.NET Core?

A7: ASP.NET Core supports a variety of configuration providers, including:

  • Azure Key Vault Configuration Provider – for securing and managing secrets.
  • Memory Configuration Provider – for setting configuration values programmatically.
  • XML Configuration Provider – for reading XML files.
  • INI Configuration Provider – for reading INI files.

To use these providers, you simply need to configure them in your Program.cs or Startup.cs file:

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                var settings = config.Build();
                config.AddAzureKeyVault($"https://{settings["KeyVault:Name"]}.vault.azure.net/",
                    settings["KeyVault:ClientId"],
                    settings["KeyVault:ClientSecret"]);
            })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

Q8: How can I handle sensitive data in ASP.NET Core configuration?

A8: Handling sensitive data in ASP.NET Core applications can be done using several strategies, including:

  • Environment variables to store sensitive data outside the application.
  • Azure Key Vault to securely store and manage secret keys and sensitive data.
  • User secrets to store secrets in a file stored outside the source code (used primarily for development).
  • Configuration transforms to apply different configurations for different environments.

For example, to use Azure Key Vault:

  1. Install the necessary NuGet package Azure.Extensions.AspNetCore.Configuration.Secrets.
  2. Register the Key Vault by configuring your Program.cs:
public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((hostingContext, config) =>
        {
            var settings = config.Build();
            config.AddAzureKeyVault($"https://{settings["KeyVault:Name"]}.vault.azure.net/",
                settings["KeyVault:ClientId"],
                settings["KeyVault:ClientSecret"]);
        })
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });

Q9: Can I use a custom configuration provider in ASP.NET Core?

A9: Yes, you can create and use a custom configuration provider in ASP.NET Core if you need to read configuration from a data source that is not supported out-of-the-box. This involves creating a class that implements the IConfigurationProvider interface and, optionally, a IConfigurationSource class to set up and return your provider. Custom providers can be used to read from databases, cloud storage, or other unconventional sources.

Here’s a simplified example of a custom configuration provider:

public class CustomConfigProvider : IConfigurationProvider
{
    private readonly string _filePath;

    public CustomConfigProvider(string filePath)
    {
        _filePath = filePath;
    }

    public void Load()
    {
        try
        {
            var contents = File.ReadAllText(_filePath);
            var data = JsonConvert.DeserializeObject<Dictionary<string, string>>(contents);
            Data = data;
        }
        catch (IOException ex)
        {
            Debug.WriteLine(ex.Message);
        }
    }

    public IDictionary<string, string> Data { get; } = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

    public bool TryGet(string key, out string value)
    {
        return Data.TryGetValue(key, out value);
    }

    public void Set(string key, string value)
    {
        Data[key] = value;
    }
}

public class CustomConfigSource : IConfigurationSource
{
    private readonly string _filePath;

    public CustomConfigSource(string filePath)
    {
        _filePath = filePath;
    }

    public IConfigurationProvider Build(IConfigurationBuilder builder)
    {
        return new CustomConfigProvider(_filePath);
    }
}

// Register custom provider
public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((hostingContext, config) =>
        {
            config.Add(new CustomConfigSource("custom_config.json"));
        })
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });

Q10: How can I handle configuration changes at runtime in ASP.NET Core?

A10: ASP.NET Core supports reloading configuration data at runtime for providers that support change detection, such as appsettings.json and Environment Variables. To enable this feature:

  1. When configuring the JSON configuration sources, use the ReloadOnChange option:
public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((hostingContext, config) =>
        {
            config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
            config.AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", optional: true, reloadOnChange: true);
        })
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });
  1. For environment variables, the values are loaded once at the start of the application and will not automatically reload at runtime. However, you can manually check for changes and reload configuration if needed.

By implementing IConfigurationRefresher and using IConfigurationRoot.Reload() method, you can also reload the configuration programmatically in response to specific events or triggers.

You May Like This Related .NET Topic

Login to post a comment.