我有一个 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();
Run Code Online (Sandbox Code Playgroud)
如你看到的, appsettings.json文件应该有一个APPINSIGHTS_INSTRUMENTATIONKEY密钥,并且在开发环境中读取它很好。
现在,对于生产,我想覆盖它 APPINSIGHTS_INSTRUMENTATIONKEY通过在 Azure 应用程序设置 Web 界面中添加具有相同密钥的设置密钥。
但是,当我将我的 webjob 部署到 Azure 时,它仍然具有来自appsettings.json. 为了强制我的 webjob 具有 Azure 应用程序设置中的覆盖密钥,我必须从appsettings.json.
有没有办法让我的 webjob 使用 Azure 应用程序设置而不必从中删除密钥appsettings.json?
问题是 Azure 应用设置是通过环境变量发送的;并且,您首先加载环境变量,然后使用 appsettings.json 覆盖:
.ConfigureAppConfiguration((hostContext, configApp) =>
{
configApp.AddEnvironmentVariables();
configApp.AddJsonFile("appsettings.json", optional: false);
})
Run Code Online (Sandbox Code Playgroud)
将此反转为
.ConfigureAppConfiguration((hostContext, configApp) =>
{
configApp.AddJsonFile("appsettings.json", optional: false);
configApp.AddEnvironmentVariables();
})
Run Code Online (Sandbox Code Playgroud)
它将首先加载您的 appsettings.json,然后使用环境变量覆盖。