Azure WebJobs无法使用Azure应用程序设置覆盖appsettings.json配置文件

8

我有一个Azure Web作业(.NET Core 2.2),在启动时像这样从配置中读取一些设置:

var builder = new HostBuilder()
    .UseEnvironment(Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"))
    .ConfigureWebJobs()
    .ConfigureAppConfiguration((hostContext, configApp) =>
    {
        configApp.AddEnvironmentVariables();
        configApp.AddJsonFile("appsettings.json", optional: false);
    })
    .ConfigureLogging((hostingContext, logging) =>
    {
        logging.AddConsole();

        var instrumentationKey = hostingContext.Configuration["APPINSIGHTS_INSTRUMENTATIONKEY"];
        if (!string.IsNullOrEmpty(instrumentationKey))
        {
            Console.Writeline(instrumentationKey); // <- this always outputs key from appsettings.json, not from Azure Settings
            logging.AddApplicationInsights(instrumentationKey);
        }
    })
    .UseConsoleLifetime();     

如您所见,appsettings.json文件应该有一个APPINSIGHTS_INSTRUMENTATIONKEY键,并且在开发环境中已经成功读取它。

现在,在生产环境中,我想通过在Azure应用程序设置Web界面中添加具有相同键的设置来覆盖此APPINSIGHTS_INSTRUMENTATIONKEY键。

然而,当我将我的Web作业部署到Azure时,它仍然具有来自appsettings.json的旧App Insights密钥。为了强制我的Web作业使用来自Azure Application设置的覆盖密钥,我必须删除appsettings.json中的App Insights密钥。

是否有一种方法让我的Web作业在不必删除appsettings.json中的键的情况下使用Azure应用程序设置?

1个回答

7
问题在于Azure应用程序设置是通过环境变量发送的;并且你首先加载环境变量,然后再使用appsettings.json进行覆盖。
.ConfigureAppConfiguration((hostContext, configApp) =>
    {
        configApp.AddEnvironmentVariables();
        configApp.AddJsonFile("appsettings.json", optional: false);
    })

将此反转为

.ConfigureAppConfiguration((hostContext, configApp) =>
    {
        configApp.AddJsonFile("appsettings.json", optional: false);
        configApp.AddEnvironmentVariables();
    })

它将首先加载您的appsettings.json文件,然后使用环境变量覆盖。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接