【问题标题】:How to provide a default app configuration setting value when keyvault value is missing?缺少 keyvault 值时如何提供默认应用程序配置设置值?
【发布时间】:2023-02-20 22:52:49
【问题描述】:

我已将我的 Azure 应用程序配置为在配置设置中使用密钥保管库引用。一般情况下一切正常,但是当我希望设置具有默认值以防它从密钥库中丢失时会出现问题。

这是我的简化代码示例:

public class MySettings
{
    public bool DoSomethingSpecial { get; set; }

    public string SomeStringSetting { get; set; }
}

启动:

serviceCollection.Configure<MySettings>(x =>
{
    configuration.Bind("MyApp:MySettings", x);
});

Azure 应用程序配置设置:

MyApp__MySettings__DoSomethingSpecial
@Microsoft.KeyVault(SecretUri=https://myapp.vault.azure.net/secrets/MyApp--MySettings--DoSomethingSpecial)

如果我不将 DoSomethingSpecial = false 添加到密钥库,应用程序将在启动时抛出错误:

Failed to convert configuration value at 'MyApp:MySettings:DoSomethingSpecial' to type 'System.Boolean'. @Microsoft.KeyVault(SecretUri=https://andromeda-keyvault-dev.vault.azure.net/secrets/MyApp--MySettings--DoSomethingSpecial) is not a valid value for Boolean. String '@Microsoft.KeyVault(SecretUri=https://andromeda-keyvault-dev.vault.azure.net/secrets/MyApp--MySettings--DoSomethingSpecial)' was not recognized as a valid Boolean. 

这意味着 Azure 将缺少的密钥保管库引用视为原始文字字符串。

我没有 appsettings.json 中提到的设置 - 那里不需要。

我的Program.cs 是非常基本的老式 .NET Core 应用程序启动器:

    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration((hostingContext, config) =>
                {
                    config.AddEnvironmentVariables();
                })
                .UseStartup<Startup>();

    }

如果缺少密钥保管库值,是否有任何好的方法来获得默认的 false 值?

目前,我想到的唯一(丑陋的)解决方法是try .. catch serviceCollection.Configure&lt;MySettings&gt; 中 MySettings 的每个设置字段。

【问题讨论】:

  • 请分享您的appsettings.jsonProgram.cs 文件。
  • @Harshitha 更新了问题。尽管这些文件与此设置没有任何关系 - 设置环境变量只是从 Azure 上的 Web 应用程序配置中挑选出来的。

标签: .net configuration azure-keyvault


【解决方案1】:

如果您在 appsettings.json 中设置了相应的设置,如果在 AzureKeyVault 中找不到它们,ASP.NET Core 将选取它们。

是这样的:

{
  "MyApp" : 
  { 
     "MySettings": 
     {
       "DoSomethingSpecial" :"12345"
     }
   }
}

【讨论】:

    猜你喜欢
    • 2018-08-19
    • 2019-11-10
    • 1970-01-01
    • 2019-02-21
    • 2011-08-21
    • 2017-07-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多