首页 > 解决方案 > 如何在 .NET 6.0 中构建 WebApplication 构建器之前访问配置变量?

问题描述

所以我的问题是,在 .NET 6 中构建构建器之前如何访问配置?

在 .NET 5 中,我们Startup.cs分解为三个函数:

通过这个设置,我能够声明一个私有只读变量来存储和使用整个 Startup.cs 中的配置

private readonly IConfigurationRoot _config; // The variable in question.
public Startup(IWebHostEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile($"appsettings.json", optional: false, reloadOnChange: true)
            .AddEnvironmentVariables();

        _config = builder.Build(); // Initializing the configuration to be access in ConfigureServices()
    }

我会_config在设置服务时经常使用该变量......例如:

// Example .NET 5 ConfigureServices.
services.AddSession(options =>
        {
            options.Cookie.Name = _config["Auth:AzureAd:SessionCookieName"];
            options.Cookie.HttpOnly = true;
            options.Cookie.IsEssential = true;
        });

但是,我知道在 .NET 6 中访问 Program.cs 中的配置的唯一方法是在创建 WebApplication 构建器之后var app = builder.Build();

问题是,您无法在构建构建器后修改服务。因此,在需要访问 appsettings/配置文件的这行代码之前,我拥有所有这些服务配置。

所以我的问题是,在 .NET 6 中构建构建器之前如何访问配置?

标签: c#asp.netasp.net-mvc.net-5.net-6.0

解决方案


推荐阅读