Search code examples
c#asp.net-core

How to add new key/values to "IConfiguration" in ASP.NET Core


The "Configuration" object loads all appsettings.json content successfully (with "CreateDefaultBuilder" in Program.cs). The same "Configuration" object is accessible in "Startup.cs" as well (as it is injected by framework itself).

Now, in "Startup.ConfigureServices", I would like add add more entries to "Configuration" object and access it in "Startup.Configure" and in other classes (like controllers, etc.)

In simple words, I would like to have something like the following:

Configuration.add("MyNewKey", "MyNewValue"); //HOW TO DO THIS

At this moment, I don't want to use any structured types.

Is this possible at all?


Solution

  • Is this possible at all?

    It is possible. We can set a configuration value in the Startup.ConfigureServices method and access it in the "Startup.Configure" and in other classes (like controllers, etc.) You could check the following sample code (Asp.net core 3.1 MVC application):

    Startup.cs:

    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
    
        // using get and set accessor 
        public IConfiguration Configuration { get; set; }
    
        public void ConfigureServices(IServiceCollection services)
        {
            Configuration["MyNewKey"] = "AAA";  //set the configuration value.
            services.AddControllersWithViews();
            services.AddRazorPages();
        } 
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();
    
            app.UseRouting();
    
            app.UseAuthentication();
            app.UseAuthorization();
    
            var result = Configuration["MyNewKey"]; //access the configuration value.
    
            app.UseEndpoints(endpoints =>
            { 
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
                
            });
        }
    }
    

    HomeController.cs:

    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly IConfiguration _configuration;
    
        public HomeController(ILogger<HomeController> logger, IConfiguration configuration)
        {
            _logger = logger;
            _configuration = configuration;
        }
    
        public IActionResult Index()
        {
            var value = _configuration["MyNewKey"];
            return View();
        }
    

    The debug screenshot as below:

    enter image description here