Asp.Net Core Custom Configuration Sections 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 Custom Configuration Sections

Explain in Detail and Show Important Info: ASP.NET Core Custom Configuration Sections

Introduction to ASP.NET Core Configuration

Configuration in ASP.NET Core refers to data that an application uses to control its behavior. The configuration system is designed for flexibility and can draw settings from various sources such as JSON files (appsettings.json), XML files, environment variables, command-line arguments, and more. However, in complex applications, default configurations may not suffice; therefore, developers often opt to create custom configuration sections.

Why Use Custom Configuration Sections?

Custom configuration sections enable you to organize and manage application settings more efficiently. By creating structured custom sections, you can:

  • Separate Concerns: Divide settings logically based on functionality.
  • Maintainability: Enhance code readability and maintainability.
  • Ease of Management: Facilitate settings management across different environments or modules.
  • Reusability: Apply the same custom section across multiple projects.

Creating Custom Configuration Sections in ASP.NET Core

Step 1: Define Your Settings Model First, define a C# class to represent the structure of your custom configuration section. This class should follow simple POCO (Plain Old CLR Object) principles and use properties to reflect the settings.

// Sample configuration model
public class CustomSettings
{
    public string ApiKey { get; set; }
    public int Timeout { get; set; }
    public ConnectionInfo Connection { get; set; }
}

public class ConnectionInfo
{
    public string Host { get; set; }
    public int Port { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
}

Step 2: Add Your Custom Configuration Section to appsettings.json Next, add the custom settings in the appsettings.json file according to the structure of the defined class.

{
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft.AspNetCore": "Warning"
        }
    },
    "CustomSettings": {
        "ApiKey": "12345-abcde-67890-fghij",
        "Timeout": 30,
        "Connection": {
            "Host": "localhost",
            "Port": 5432,
            "UserName": "admin",
            "Password": "securepassword"
        }
    }
}

Step 3: Bind the Configuration Section to the Settings Model In ASP.NET Core, binding configuration settings to a C# object is straightforward. Use the services.Configure<T>() method in your Startup.cs file (or Program.cs if using .NET 6 and later).

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

public class Startup
{
    public IConfiguration Configuration { get; }

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

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
        
        // Bind the CustomSettings section to the CustomSettings class
        services.Configure<CustomSettings>(Configuration.GetSection("CustomSettings"));
    }

    // ...
}

Step 4: Inject and Access the Configured Settings You can now access your custom settings through IOptions<T> or similar interfaces.

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;

public class SettingsController : ControllerBase
{
    private readonly CustomSettings _customSettings;

    public SettingsController(IOptions<CustomSettings> options)
    {
        _customSettings = options.Value;
    }

    [HttpGet("api/settings")]
    public IActionResult GetSettings()
    {
        var response = new 
        {
            ApiKey = _customSettings.ApiKey,
            Timeout = _customSettings.Timeout,
            Host = _customSettings.Connection.Host,
            Port = _customSettings.Connection.Port,
            UserName = _customSettings.Connection.UserName
            // Avoid exposing password in production responses
        };

        return Ok(response);
    }
}

Step 5: Using Named Options (Optional but Recommended) Named options allow you to differentiate between multiple configuration instances of the same type. This is particularly useful in larger applications or when integrating with third-party libraries.

// In Startup.cs
services.Configure<CustomSettings>("ExternalApi", Configuration.GetSection("CustomSettings"));

// In the controller
private readonly CustomSettings _externalApiSettings;

public SettingsController(IOptionsSnapshot<CustomSettings> options)
{
    _externalApiSettings = options.Get("ExternalApi");
}

Best Practices for Custom Configuration Sections

  • Environment-Specific Configurations: Use appsettings.{Environment}.json files to override settings based on the runtime environment (e.g., Development, Staging, Production).
  • Validation: Implement validation logic within custom classes constructors or use data annotations to enforce constraints on your settings.
  • Security: Do not store sensitive information like passwords in plain text. Consider encrypting or using secure vaults.
  • Documentation: Keep comments in JSON files and classes to make it easier for team members to understand the purpose and usage of each setting.

Advanced Configuration Techniques

  • Bind Hierarchical Settings: If your settings have a deep hierarchy, your POCO class must mirror this structure accurately.
  • Configure Options: The ConfigureOptions<TOptions> pattern allows you to register a configuration delegate that sets the options values during the options service provider registration lifecycle.
  • File Providers: Utilize FileProvider objects with AddJsonFile() method or others to load settings from alternative locations.
  • In-Memory Configuration: Temporarily add configuration providers that source settings from memory using InMemoryConfigurationSource().
  • Reload Options on File Change: Use IOptionsMonitor<TOptions> or IOptionsSnapshot<TOptions> for reloading options automatically when linked configuration files are changed.

Conclusion

Mastering customization of configuration sections in ASP.NET Core empowers developers to manage application settings more effectively, promoting cleaner and more maintainable code. By following these guidelines and practices, you can harness the full potential of the configuration system to streamline development processes and ensure robust application settings management across different environments.


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 Custom Configuration Sections

Step 1: Create a New ASP.NET Core Project

First, create a new ASP.NET Core project. You can do this via Visual Studio or the .NET CLI.

Using Visual Studio:

  1. Open Visual Studio.
  2. Go to File > New > Project.
  3. Select an ASP.NET Core Web Application project template (e.g., MVC, Empty).
  4. Configure your project name and location, then click Create.

Using .NET CLI:

dotnet new mvc -n CustomConfigExample
cd CustomConfigExample

Step 2: Define a Custom Configuration Section

In your project, define a class that represents your custom configuration section. This class will have properties corresponding to the settings in your section.

For example, let's create a custom configuration section called MySettings.

Create the Configuration Class

Open the Models folder and create a new class named MySettings.cs.

// Models/MySettings.cs
namespace CustomConfigExample.Models
{
    public class MySettings
    {
        public string ApiKey { get; set; }
        public string ConnectionString { get; set; }
        public NestedSettings NestedSettings { get; set; }
    }

    public class NestedSettings
    {
        public int Timeout { get; set; }
        public string Environment { get; set; }
    }
}

Step 3: Update appsettings.json with Custom Configuration

Next, update your appsettings.json file to include the custom configuration section.

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "MySettings": {
    "ApiKey": "your-api-key-value-here",
    "ConnectionString": "Server=localhost;Database=YourDB;User Id=your_user_id;Password=your_password;",
    "NestedSettings": {
      "Timeout": 60,
      "Environment": "Development"
    }
  }
}

Step 4: Bind the Custom Configuration Section

In your Startup.cs or Program.cs file (depending on the version of ASP.NET Core), bind the custom configuration section to the configuration class you created.

Using Startup.cs (ASP.NET Core 2.1 - 3.1)

public class Startup
{
    public IConfiguration Configuration { get; }

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

    public void ConfigureServices(IServiceCollection services)
    {
        // Bind the custom configuration section to the Model class
        services.Configure<MySettings>(Configuration.GetSection("MySettings"));

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

    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?}");
        });
    }
}

Using Minimal Hosting Model with Program.cs (ASP.NET Core 6+)

var builder = WebApplication.CreateBuilder(args);

// Bind the custom configuration section to the Model class
builder.Services.Configure<MySettings>(builder.Configuration.GetSection("MySettings"));

builder.Services.AddControllersWithViews();

var app = builder.Build();

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();

Step 5: Use the Custom Configuration in Your Controllers

Once the configuration is bound to the class, you can inject it into any controllers where you need to use these settings.

// Controllers/HomeController.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using CustomConfigExample.Models;

namespace CustomConfigExample.Controllers
{
    public class HomeController : Controller
    {
        private readonly MySettings _mySettings;

        public HomeController(IOptions<MySettings> mySettings)
        {
            _mySettings = mySettings.Value;
        }

        public IActionResult Index()
        {
            ViewBag.ApiKey = _mySettings.ApiKey;
            ViewBag.ConnectionString = _mySettings.ConnectionString;
            ViewBag.Timeout = _mySettings.NestedSettings.Timeout;
            ViewBag.Environment = _mySettings.NestedSettings.Environment;

            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}

Step 6: Display Configuration Values in Views

Now, in your view, you can display these configuration values from the ViewBag.

<!-- Views/Home/Index.cshtml -->
@{
    ViewData["Title"] = "Home Page";
}

<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <p>API Key: @ViewBag.ApiKey</p>
    <p>Connection String: @ViewBag.ConnectionString</p>
    <p>Timeout: @ViewBag.Timeout</p>
    <p>Environment: @ViewBag.Environment</p>
</div>

Step 7: Run Your Project

Finally, run your project to see the custom configuration values displayed on the homepage.

Using Visual Studio:

  1. Press F5 or click the Start button.

Using .NET CLI:

dotnet run

Navigate to the home page (https://localhost:<port>/), and you should see the custom configuration values displayed.

Example Output

When you navigate to the home page, you should see something like this:

You May Like This Related .NET Topic

Login to post a comment.