如何从 C# - Web 应用程序向 Azure 资源添加标签

How to Add Tags to Azure Resource from a C# - Web Application

如何在我的 ASP.NET 应用程序中使用 C# 代码将标签添加到 azure 资源。 我正在尝试创建一个 azure 标签管理门户。

我找到了这个 但它是关于向资源组添加标签的。此外,该图书馆似乎已被弃用。如果有人知道如何将标签附加到资源,请帮助。

注意:(i)我已尝试 Azure ServiceManagement API,但我发现 API 不支持将标签附加到资源。 (ii) 如果没有其他方法,powershell Cmdlet 是否是一个可行的选择?

PowerShell 可以轻松做到这一点,您可以使用以下命令:

PS C:\> Set-AzureRmResource -Tag @( @{ Name="tag_name"; Value="tag_value" }) -ResourceId <resource_id>

查看 this article 了解详情。

如果有人有兴趣尝试通过 REST API, 我在使用 Fiddler 监视 powershell 绑定流量后发现了这一点。请注意标记为 json-payload.

https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/Microsoft.Compute/virtualMachines/{VM-Name}

PATCH **https://management.azure.com/subscriptions/6dcd{subscrID}e8f/resourceGroups/css-dev/providers/Microsoft.Sql/servers/css-development/databases/css-dev?api-version=2014-04-01 HTTP/1.1**
Authorization: Bearer sDSEsiJKV1QiLCJhbG[<PARTIALLY REMOVED BY KIRAN FOR SECURITY REASON>]XDvZBJG5Jhh0rivehvDS
User-Agent: AzurePowershell/v1.0.0.0
ParameterSetName: Resource that resides at the subscription level.
CommandName: Set-AzureRmResource
Content-Type: application/json; charset=utf-8
Host: management.azure.com
Content-Length: 52
Expect: 100-continue
Connection: Keep-Alive

**{
  "tags": {
    "displayName": "AzureV1"
  }
}**

遵循这个link在AD和服务原则中创建客户端应用程序。记下 tenantId、ClientId 和 ClientKey

https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal

找到资源,添加/更新标签并打补丁。

var serviceCreds = await ApplicationTokenProvider.LoginSilentAsync(tenantId, clientId, clientKey);
var resourceClient = new ResourceManagementClient(serviceCreds);
resourceClient.SubscriptionId = subscriptionId;

GenericResource genericResource = resourceClient.Resources.Get("some-resource-group", "Microsoft.DocumentDB", "", "databaseAccounts", "some-resource", "2016-03-31");

genericResource.Tags.Add("Version", "1.0");

resourceClient.Resources.CreateOrUpdate("some-resource-group", "Microsoft.DocumentDB", "", "databaseAccounts", "some-resource", "2016-03-31", genericResource);