c# - 无法从 Azure 应用程序配置服务读取设置

标签 c# azure asp.net-core azure-app-configuration

我在 .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 字段中的所有值,如下面的屏幕截图所示。

enter image description here

enter image description here

谁能告诉我我做错了什么?

最佳答案

根据the documentation :

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/

相关文章:

c# - C# 程序中 SQL Server 的 OleDB 连接字符串

azure - 如何更改部署在Azure Web App中的Wiki JS favicon?

azure - 如何在Azure Kubernetes服务部署期间修改默认Docker基本镜像

c# - 找不到 IdentityServer4 测试服务器

c# - 如何在 ios xamarin studio 中生成 xml 文档文件?

c# - 防止非 SELECT SQL 语句

sql - 连接到数据库时 Azure SQL 数据库超时问题

asp.net-core - 从 VS 2017 发布 .net core 应用程序

asp.net-core - 如何从 Azure B2C 获取 ASP Core 中的 OID 声明

c# - 如何在调用 .LoadXml() 之前检查字符串输入中的有效 xml