简体   繁体   English

如何在 ASP.NET 内核中向“IConfiguration”添加新的键/值

[英]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). “配置”object 成功加载所有 appsettings.json 内容(在 Program.cs 中使用“CreateDefaultBuilder”)。 The same "Configuration" object is accessible in "Startup.cs" as well (as it is injected by framework itself).同样的“配置”object 也可以在“Startup.cs”中访问(因为它是由框架本身注入的)。

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.)现在,在“Startup.ConfigureServices”中,我想向“Configuration”object 添加更多条目,并在“Startup.Configure”和其他类(如控制器等)中访问它

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?这可能吗?

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.ConfigureServices 方法中设置配置值,并在“Startup.Configure”和其他类(如控制器等)中访问它。您可以查看以下示例代码(Asp.net core 3.1 MVC 应用程序):

Startup.cs:启动.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: 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:调试截图如下:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM