我在 .Net 7 中有一个正在运行的 Web API。Web API 从 appsettings.json
本地文件读取配置设置,一切都运行良好。
现在我想使用 Azure 应用程序配置服务来存储设置。我在 Azure 订阅中创建了 Azure 应用程序配置服务,并上传了本地 appsettings.json 文件。我可以在那里看到我的所有设置,因此导入也有效。导入时,我选择使用 __
作为分隔符。
现在,我在 Program.cs
中进行了以下代码更改,以从 Azure 读取设置:
private static IHostBuilder CreateHostBuilder(string[] args)
{
return Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
_ = webBuilder.UseStartup<Startup>();
_ = webBuilder.ConfigureAppConfiguration((configurationBuilder) =>
{
configurationBuilder.Sources.Clear();
configurationBuilder.AddAzureAppConfiguration(options =>
{
options.Connect(new Uri("https://myappconfig.azconfig.io"),
new DefaultAzureCredential());
}, false);
configurationBuilder.Build();
});
});
}
同样,这段代码运行良好并且没有抛出任何错误。
但是,当我尝试读取 Startup.cs
文件中的设置时,我没有取回设置。例如,下面是以前运行良好的代码:
public void ConfigureServices(IServiceCollection services)
{
//Inject API Settings
var apiSettings = new ApiSettings();
Configuration.GetSection("ApiSettings").Bind(apiSettings);
services.AddSingleton(apiSettings);
// Rest of my code
}
以前,我曾经让 apiSettings
的所有字段都获得正确的值,但现在我将它们全部设置为 null。
有趣的是,当我看到 Configuration
的值时,我看到 Data
字段中的所有值,如下面的屏幕截图所示。
谁能告诉我我做错了什么?
最佳答案
Hierarchical keys
- Within the Configuration API, a colon separator (:) works on all platforms.
- In environment variables, a colon separator may not work on all platforms. A double underscore, __, is supported by all platforms and is automatically converted into a colon :.
- In Azure Key Vault, hierarchical keys use -- as a separator. The Azure Key Vault configuration provider automatically replaces -- with a : when the secrets are loaded into the app's configuration.
我建议使用 :
作为分隔符导入配置。因为它们不是环境变量,所以我会使用默认分隔符。
关于c# - 无法从 Azure 应用程序配置服务读取设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75735538/