Azure 应用服务中的 .NET Core WebJob 配置

.NET Core WebJob configuration in Azure App Service

我已经将 Web 作业编写为 .NET Core 控制台应用程序 (exe),它具有 appsettings.json.

如何在 Azure 中配置 WebJob?基本上我想与 Web 应用共享一些设置,例如连接字符串,这些设置是通过 App Service 的应用程序设置配置的。

从我们的 ASP.NET 核心获取这些设置的方法是访问注入的环境变量。

因此我们必须将这些环境变量加载到 Startup.cs 文件中的配置中:

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();
    }

appsettings.json 文件的示例为:

如果你想获取在 appsettings.json 文件中定义的名为 "Redis" 的连接字符串,我们可以通过我们的配置获取它:

Configuration["ConnectionStrings:Redis"].

您可以在 Azure 门户上的 webapp 的 Appsettings 中设置此配置:

我们还可以使用 Configuration.GetConnectionString("Redis") 从我们的 appsettings.json 文件中获取开发连接字符串,并在部署应用程序时覆盖它,在我们的 Web 应用程序的连接字符串面板中设置一个不同的字符串,并且运行 在 Azure 中。

更多细节,你可以参考这个article

CloudConfigurationManager class 非常适合这种情况,因为它将从 所有环境(网络作业配置和基本应用配置)。

Install-Package Microsoft.WindowsAzure.ConfigurationManager

那就这样用吧

var val = CloudConfigurationManager.GetSetting("your_appsetting_key");

唯一的缺点是只能从 appSettings 部分而不是 CloudConfigurationManager 的连接字符串部分读取。 如果您想在 Web 作业和基本 Web 应用程序之间共享连接,那么我会在 Web 应用程序的应用程序设置部分使用唯一键定义连接字符串。

我更喜欢通过在本地项目的 launchSettings.json 中设置环境变量并在 Azure 应用服务设置中设置相同的变量来实现此目的。

优点是您的应用程序始终使用环境变量,更重要的是,没有密钥最终会出现在您的源代码管理中,因为您不必部署 launchSettings.json