我正在努力从Azure Webjob SDK 3.0项目中的appsettings.json文件中读取任何变量。
我在用:
我尝试过以下方法:
System.Configuration.ConfigurationManager.AppSettings["ApiUrl"]
但是这会返回null并且无法读取。我已经检查了SO上的文档和其他问题,但目前它就像在大海捞针一样。
Program.cs中
static async Task Main(string[] args)
{
var builder = new HostBuilder()
.ConfigureWebJobs(b =>
{
b.AddAzureStorageCoreServices()
.AddAzureStorage()
.AddTimers();
b.UseHostId(Environment.UserName.ToLowerInvariant());
})
.ConfigureAppConfiguration((b, c)=>
{
var env = b.HostingEnvironment;
c.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
c.AddCommandLine(args);
c.AddEnvironmentVariables();
c.Build();
})
.ConfigureLogging((context, b) =>
{
b.SetMinimumLevel(LogLevel.Debug);
b.AddConsole();
string appInsightsKey = context.Configuration["APPINSIGHTS_INSTRUMENTATIONKEY"];
if (!string.IsNullOrEmpty(appInsightsKey))
{
b.AddApplicationInsights(o => o.InstrumentationKey = appInsightsKey);
}
})
.UseConsoleLifetime();
var host = builder.Build();
using (host)
{
await host.RunAsync();
}
}
Functions.cs
public static async Task ProcessAsync([TimerTrigger("0 */3 * * * *")] TimerInfo timerInfo, ILogger log)
{
//I want to read my appsettings.json here!
}
appsettings.json示例:
{
"AzureWebJobsDashboard": "################",
"AzureWebJobsStorage": "################",
"ApiUrl": "#############",
"APPINSIGHTS_INSTRUMENTATIONKEY": "############"
}
忽略这一点 - 仍然无法正常工作
刚想通了!在我的Functions类的开头初始化它为我修复了它:
private readonly IConfiguration _configuration;
public Functions(IConfiguration configuration)
{
_configuration = configuration;
}
public static async Task ProcessAsync([TimerTrigger("0 */3 * * * *")] TimerInfo timerInfo, ILogger log)
{
var conf = _configuration["ApiUrl"];
}
这有效,但导致WebJob作为一个函数运行。每个运行应该在日志中的WebJob函数parent下按每个运行进行分解。令人难以置信的沮丧。
如果有人可以提供帮助,请告诉我。