首页 > 解决方案 > 如何通过 C# 从 Azure Webjob 更新 Azure AppSettings?

问题描述

我在 Azure Web 应用程序中托管了 Azure Web 作业,它每小时运行一次,我需要将 Web 作业运行时间编写为键值对。下次 Webjob 运行时,它将选择上次运行时间并执行其操作。我正在考虑在 Azure App 服务的 Azure AppSettings 中添加键值对,但我无法修改任何代码来更新 Azure AppSettings 中的值。

谁能告诉我代码?请让我知道这是否是一种好方法,或者我应该使用 Azure 存储容器来存储 Last Batch Run Time 值。

标签: azureazure-webjobsazure-web-app-serviceappsettings

解决方案


但我无法修改任何代码来更新 Azure AppSettings 中的值。

您可以使用Microsoft.WindowsAzure.Management.WebSites来实现它。

var credentials = GetCredentials(/*using certificate*/);
using (var client = new WebSiteManagementClient(credentials))
{
    var currentConfig = await client.WebSites.GetConfigurationAsync(webSpaceName,
                                                                    webSiteName);
    var newConfig = new WebSiteUpdateConfigurationParameters
                    {
                        ConnectionStrings = null,
                        DefaultDocuments = null,
                        HandlerMappings = null,
                        Metadata = null,
                        AppSettings = currentConfig.AppSettings
    };
    newConfig.AppSettings[mySetting] = newValue;
    await client.WebSites.UpdateConfigurationAsync(webSpaceName, webSiteName,
                                                   newConfig);
}

或者使用 Azure Fluent Api,参考这个SO thread


推荐阅读