【发布时间】:2020-02-17 10:42:17
【问题描述】:
我正在编写一个 WebApi 来跟踪我的小狗的行为(如厕时间、板条箱训练等)。该 api 有一个用 Blazor 编写的前端组件,但这不是这个问题的一部分。
在我的 github 项目中,我从不使用 appsettings.json 文件,因为担心不小心提交它并因此暴露任何秘密。相反,我想像这样添加我自己的 appsettings 文件:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(config => {
var basePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var fileName = "puppytrackersettings.json";
var fullPath = Path.Combine(basePath, fileName);
if(File.Exists(fullPath))
{
config.SetBasePath(basePath);
config.AddJsonFile(fileName, optional: true);
}
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
这样,设置文件可以保存在“我的文档”文件夹(Linux 上的“/”)中,远离源代码。
问题
问题是配置仅在 CreateHostBuilder() 方法中使用此添加的 json 文件更新。一旦配置在 Startup.cs 中被激活,配置就会回到它的默认配置。我看到配置提供程序在输入 CreateHostBuilder() 之前是 5,然后在我添加我的 json 文件后它会跳到 6,但是当 Startup.ConfigureServices() 运行时,配置又回到了5。
我尝试了多种方法来为 webapi 创建配置,但都没有奏效。
解决方法
到目前为止,我的解决方法是在 VS 中使用应用程序机密,但由于某些设置(例如 Application Insights Telemetry Key)是共享的,因此在所有微服务之间进行复制是很痛苦的,因为我无法指向现有应用程序秘密。
有谁知道我做错了什么,或者如何正确地做到这一点?
.Net Core 的版本是 3.1.101 视觉工作室:16.4.5
【问题讨论】:
标签: c# asp.net-core configuration