问题
I've written web job as .NET Core Console Application (exe), that has appsettings.json.
How do I configure the WebJob in Azure? Basically I want to share some settings like connection string with the web app, that is configured trough App Service's Application Settings.
回答1:
The way to get these settings from our ASP.NET Core is accessing to the injected environment variables.
Hence we have to load these environment variables into our Configuration in the Startup.cs file:
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
An example of appsettings.json file would be:
If you want to get the connection string named "Redis" defined in the appsettings.json file we could get it through our Configuration:
Configuration["ConnectionStrings:Redis"]
.
You could set this Configuration in Appsettings in webapp on azure portal:
Also we can use Configuration.GetConnectionString("Redis")
to get a development connection string from our appsettings.json file and override it setting a different one in the Connection String panel of our Web App when the application is deployed and running in Azure.
For more detail, you could refer to this article.
回答2:
I prefer doing this through setting environment varibles in launchSettings.json
in my local project and setting the same ones in Azure App Service settings.
Advantage is that your application always uses environment variables and, more important one, no keys end up in your source control since you don't have to deploy launchSettings.json
.
回答3:
The CloudConfigurationManager class is perfect for this situation as it will read configuration settings from all environments (the web jobs config and the base app config).
Install-Package Microsoft.WindowsAzure.ConfigurationManager
Then use it like this
var val = CloudConfigurationManager.GetSetting("your_appsetting_key");
The only downside is that it is only possible to read from the appSettings sections and not the connectionstring section with the CloudConfigurationManager. If you want to share connectionsting between the web job and the base web app, then I would define the connectionstring in the appsetting section of the web app with an unique key.
来源:https://stackoverflow.com/questions/49256615/net-core-webjob-configuration-in-azure-app-service