在 C# 中更新远程 Function App 应用程序设置

Updating remote Function App Application Settings in C#

我目前正在编写一个预定的函数应用程序,它部分需要更新我已授予服务主体访问权限的另一个函数应用程序的应用程序设置。我需要更新的 Function App 托管在同一个应用服务计划中。

我知道我可以使用 az functionapp config appsettings set cmdlet 通过 Powershell 实现这一点,但我想知道这在 C#

中是否可行

Azure CLIAzure PowerShell Module无非是执行Azure REST API的一种方式。所以你可以直接使用 C# HttpClient 调用 REST API。

Here you can check how to call REST API endpoints using postman (i.e. how to get tokens etc.) To change appsetting you need this endpoint Web Apps - Create Or Update Configuration -> properties.appSettings.

看起来可以使用 Microsoft.Azure.Management.AppService.Fluent and Microsoft.Azure.Management.ResourceManager.Fluent 扩展库,它们是 REST 调用的包装器。

using Microsoft.Azure.Management.AppService.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using System;
using System.Threading.Tasks;

namespace Azure_Storage_Account_Key_Rotation
{
    internal async Task UpdateApplicationSetting(string appServiceResourceGroupName, string appServiceName, string appSettingName, string appSettingValue)
    {
        var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(Environment.GetEnvironmentVariable("AZURE_CLIENT_ID"),
                                                                                    Environment.GetEnvironmentVariable("AZURE_CLIENT_SECRET"),
                                                                                    Environment.GetEnvironmentVariable("AZURE_TENANT_ID"),
                                                                                    AzureEnvironment.AzureGlobalCloud);

        RestClient restClient = RestClient.Configure()
                                    .WithEnvironment(AzureEnvironment.AzureGlobalCloud)
                                    .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                                    .WithCredentials(credentials)
                                    .Build();

        WebSiteManagementClient webSiteManagementClient = new WebSiteManagementClient(restClient) { SubscriptionId = Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID") };

        var appServiceSettings = await webSiteManagementClient.WebApps.ListApplicationSettingsAsync(appServiceResourceGroupName, appServiceName);

        if (appServiceSettings.Properties.ContainsKey(appSettingName))
        {
            appServiceSettings.Properties[appSettingName] = appSettingValue;
            await webSiteManagementClient.WebApps.UpdateApplicationSettingsAsync(appServiceResourceGroupName, appServiceName, appServiceSettings);
        }
    }
}