在 ASP.NET Core 3.1 中,我们可以在启动时配置自定义 JSON 文件。步骤如下:
在项目根目录下创建一个名为 appsettings.custom.json 的 JSON 文件,此处以 appsettings.custom.json 作为示例文件名,如果需要更改文件名,修改代码中 appsettings.custom.json 对应的文件名即可。
在 Startup.cs 中的构造方法中添加以下代码:
public Startup(IConfiguration configuration)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile("appsettings.custom.json", optional: true, reloadOnChange: true) // 添加 appsettings.custom.json 文件作为可选 JSON 文件
.AddEnvironmentVariables();
Configuration = builder.Build();
}
这段代码会加载 appsettings.custom.json 文件作为可选 JSON 文件,并将其添加到配置构建器中。当文件更新时,此构造方法会重新加载文件。
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IConfiguration config)
{
// 获取 appsettings.custom.json 文件中的配置
var customConfigSection = config.GetSection("CustomConfig");
var customConfigValue = customConfigSection.GetValue("CustomConfigValue");
// 其他代码省略
}
这样就可以在启动时配置自定义 JSON 文件,读取其中的配置项,并在应用程序的任何地方使用它们了。