选项
首页首页 Skill 开发运营和 CI/CD azure-mgmt-apimanagement-dotnet

azure-mgmt-apimanagement-dotnet

microsoft/skills microsoft/skills

使用 .NET 管理平面 SDK 管理 Azure API 管理服务、API、产品、订阅、策略、用户和网关。

...展开全部
0
更新时间 2026-09-16

Azure.ResourceManager.ApiManagement (.NET)

通过 Azure 资源管理器 (Azure Resource Manager) 预配和管理 Azure API Management 资源的平面管理 SDK。

⚠️ 管理平面与数据平面

  • 本 SDK (Azure.ResourceManager.ApiManagement):创建服务、API、产品、订阅、策略、用户和组
  • 数据平面:直接调用您的 APIM 网关端点的 API

安装

dotnet add package Azure.ResourceManager.ApiManagement
dotnet add package Azure.Identity

当前版本:v1.3.0

环境变量

AZURE_SUBSCRIPTION_ID=<your-subscription-id> # 必需:Azure 订阅 ID
AZURE_TOKEN_CREDENTIALS=prod  # 仅在生产环境中使用 DefaultAzureCredential 时必需
AZURE_TENANT_ID=<tenant-id> # 用于服务主体身份验证(可选)
AZURE_CLIENT_ID=<client-id> # 用于服务主体身份验证(可选)
AZURE_CLIENT_SECRET=<client-secret> # 用于服务主体身份验证(可选)
</client-secret></client-id></tenant-id></your-subscription-id>

身份验证

using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.ApiManagement;

// 本地开发:DefaultAzureCredential。生产环境:设置 AZURE_TOKEN_CREDENTIALS=prod 或 AZURE_TOKEN_CREDENTIALS=<specific_credential>
var credential = new DefaultAzureCredential(
    DefaultAzureCredential.DefaultEnvironmentVariableName
);
// 或者在生产环境中直接使用特定的凭据:
// 请参阅 https://learn.microsoft.com/dotnet/api/overview/azure/identity-readme?view=azure-dotnet#credential-classes
// var credential = new ManagedIdentityCredential();
var armClient = new ArmClient(credential);

// 获取订阅
var subscriptionId = Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID");
var subscription = armClient.GetSubscriptionResource(
    new ResourceIdentifier($"/subscriptions/{subscriptionId}"));
</specific_credential>

资源层次结构

ArmClient
└── SubscriptionResource
    └── ResourceGroupResource
        └── ApiManagementServiceResource
            ├── ApiResource
            │   ├── ApiOperationResource
            │   │   └── ApiOperationPolicyResource
            │   ├── ApiPolicyResource
            │   ├── ApiSchemaResource
            │   └── ApiDiagnosticResource
            ├── ApiManagementProductResource
            │   ├── ProductApiResource
            │   ├── ProductGroupResource
            │   └── ProductPolicyResource
            ├── ApiManagementSubscriptionResource
            ├── ApiManagementPolicyResource
            ├── ApiManagementUserResource
            ├── ApiManagementGroupResource
            ├── ApiManagementBackendResource
            ├── ApiManagementGatewayResource
            ├── ApiManagementCertificateResource
            ├── ApiManagementNamedValueResource
            └── ApiManagementLoggerResource

核心工作流

1. 创建 API Management 服务

using Azure.ResourceManager.ApiManagement;
using Azure.ResourceManager.ApiManagement.Models;

// 获取资源组
var resourceGroup = await subscription
    .GetResourceGroupAsync("my-resource-group");

// 定义服务
var serviceData = new ApiManagementServiceData(
    location: AzureLocation.EastUS,
    sku: new ApiManagementServiceSkuProperties(
        ApiManagementServiceSkuType.Developer, 
        capacity: 1),
    publisherEmail: "[email protected]",
    publisherName: "Contoso");

// 创建服务(长时间运行的操作 - 可能需要 30 分钟以上)
var serviceCollection = resourceGroup.Value.GetApiManagementServices();
var operation = await serviceCollection.CreateOrUpdateAsync(
    WaitUntil.Completed,
    "my-apim-service",
    serviceData);

ApiManagementServiceResource service = operation.Value;

2. 创建 API

var apiData = new ApiCreateOrUpdateContent
{
    DisplayName = "My API",
    Path = "myapi",
    Protocols = { ApiOperationInvokableProtocol.Https },
    ServiceUri = new Uri("https://backend.contoso.com/api")
};

var apiCollection = service.GetApis();
var apiOperation = await apiCollection.CreateOrUpdateAsync(
    WaitUntil.Completed,
    "my-api",
    apiData);

ApiResource api = apiOperation.Value;

3. 创建产品

var productData = new ApiManagementProductData
{
    DisplayName = "Starter",
    Description = "Starter tier with limited access",
    IsSubscriptionRequired = true,
    IsApprovalRequired = false,
    SubscriptionsLimit = 1,
    State = ApiManagementProductState.Published
};

var productCollection = service.GetApiManagementProducts();
var productOperation = await productCollection.CreateOrUpdateAsync(
    WaitUntil.Completed,
    "starter",
    productData);

ApiManagementProductResource product = productOperation.Value;

// 将 API 添加到产品
await product.GetProductApis().CreateOrUpdateAsync(
    WaitUntil.Completed,
    "my-api");

4. 创建订阅

var subscriptionData = new ApiManagementSubscriptionCreateOrUpdateContent
{
    DisplayName = "My Subscription",
    Scope = $"/products/{product.Data.Name}",
    State = ApiManagementSubscriptionState.Active
};

var subscriptionCollection = service.GetApiManagementSubscriptions();
var subOperation = await subscriptionCollection.CreateOrUpdateAsync(
    WaitUntil.Completed,
    "my-subscription",
    subscriptionData);

ApiManagementSubscriptionResource subscription = subOperation.Value;

// 获取订阅密钥
var keys = await subscription.GetSecretsAsync();
Console.WriteLine($"Primary Key: {keys.Value.PrimaryKey}");

5. 设置 API 策略

var policyXml = @"
<policies><inbound><rate-limit></rate-limit><set-header><value>CustomValue</value></set-header><base></base></inbound><backend><base></base></backend><outbound><base></base></outbound><on-error><base></base></on-error></policies>";

var policyData = new PolicyContractData
{
    Value = policyXml,
    Format = PolicyContentFormat.Xml
};

await api.GetApiPolicy().CreateOrUpdateAsync(
    WaitUntil.Completed,
    policyData);

6. 备份和还原

// 备份
var backupParams = new ApiManagementServiceBackupRestoreContent(
    storageAccount: "mystorageaccount",
    containerName: "apim-backups",
    backupName: "backup-2024-01-15")
{
    AccessType = StorageAccountAccessType.SystemAssignedManagedIdentity
};

await service.BackupAsync(WaitUntil.Completed, backupParams);

// 还原
await service.RestoreAsync(WaitUntil.Completed, backupParams);

关键类型参考

类型用途
`ArmClient`所有 ARM 操作的入口点
`ApiManagementServiceResource`表示 APIM 服务实例
`ApiManagementServiceCollection`用于服务 CRUD 的集合
`ApiResource`表示 API
`ApiManagementProductResource`表示产品
`ApiManagementSubscriptionResource`表示订阅
`ApiManagementPolicyResource`服务级别策略
`ApiPolicyResource`API 级别策略
`ApiManagementUserResource`表示用户
`ApiManagementGroupResource`表示组
`ApiManagementBackendResource`表示后端服务
`ApiManagementGatewayResource`表示自托管网关

SKU 类型

SKU用途容量
`Developer`开发/测试(无 SLA)1
`Basic`入门级生产环境1-2
`Standard`中等负载1-4
`Premium`高可用性,多区域每区域 1-12
`Consumption`无服务器,按调用付费N/A

最佳实践

  1. 使用 WaitUntil.Completed 用于必须在继续之前完成的操作
  2. 使用 WaitUntil.Started 用于长时间运行的操作,如服务创建(30 分钟以上)
  3. 始终使用 DefaultAzureCredential — 切勿硬编码密钥
  4. 处理 RequestFailedException 以应对 ARM API 错误
  5. 使用 CreateOrUpdateAsync 用于幂等操作
  6. *通过 `Get方法导航层次结构**(例如,service.GetApis()`)
  7. 策略格式 — 使用 XML 格式的策略;也支持 JSON
  8. 服务创建 — Developer SKU 测试速度最快(约 15-30 分钟)

错误处理

using Azure;

try
{
    var operation = await serviceCollection.CreateOrUpdateAsync(
        WaitUntil.Completed, serviceName, serviceData);
}
catch (RequestFailedException ex) when (ex.Status == 409)
{
    Console.WriteLine("Service already exists");
}
catch (RequestFailedException ex) when (ex.Status == 400)
{
    Console.WriteLine($"Bad request: {ex.Message}");
}
catch (RequestFailedException ex)
{
    Console.WriteLine($"ARM Error: {ex.Status} - {ex.ErrorCode}: {ex.Message}");
}

参考文件

文件何时阅读
references/service-management.md服务 CRUD、SKU、网络、备份/还原
references/apis-operations.mdAPI、操作、模式、版本控制
references/products-subscriptions.md产品、订阅、访问控制
references/policies.md策略 XML 模式、范围、常见策略

相关资源

资源用途
API Management Documentation官方 Azure 文档
Policy Reference完整的策略参考
SDK Reference.NET API 参考
在 GitHub 上查看
---
name: azure-mgmt-apimanagement-dotnet
description: Manage Azure API Management services, APIs, products, subscriptions, policies, users, and gateways using the .NET management plane SDK.
license: MIT
---

# Azure.ResourceManager.ApiManagement (.NET)

Management plane SDK for provisioning and managing Azure API Management resources via Azure Resource Manager.

> **⚠️ Management vs Data Plane**
> - **This SDK (Azure.ResourceManager.ApiManagement)**: Create services, APIs, products, subscriptions, policies, users, groups
> - **Data Plane**: Direct API calls to your APIM gateway endpoints

## Installation

```bash
dotnet add package Azure.ResourceManager.ApiManagement
dotnet add package Azure.Identity
```

**Current Version**: v1.3.0

## Environment Variables

```bash
AZURE_SUBSCRIPTION_ID=<your-subscription-id> # Required: Azure subscription ID
AZURE_TOKEN_CREDENTIALS=prod  # Required only if DefaultAzureCredential is used in production
AZURE_TENANT_ID=<tenant-id> # For service principal auth (optional)
AZURE_CLIENT_ID=<client-id> # For service principal auth (optional)
AZURE_CLIENT_SECRET=<client-secret> # For service principal auth (optional)
```

## Authentication

```csharp
using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.ApiManagement;

// Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
var credential = new DefaultAzureCredential(
    DefaultAzureCredential.DefaultEnvironmentVariableName
);
// Or use a specific credential directly in production:
// See https://learn.microsoft.com/dotnet/api/overview/azure/identity-readme?view=azure-dotnet#credential-classes
// var credential = new ManagedIdentityCredential();
var armClient = new ArmClient(credential);

// Get subscription
var subscriptionId = Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID");
var subscription = armClient.GetSubscriptionResource(
    new ResourceIdentifier($"/subscriptions/{subscriptionId}"));
```

## Resource Hierarchy

```
ArmClient
└── SubscriptionResource
    └── ResourceGroupResource
        └── ApiManagementServiceResource
            ├── ApiResource
            │   ├── ApiOperationResource
            │   │   └── ApiOperationPolicyResource
            │   ├── ApiPolicyResource
            │   ├── ApiSchemaResource
            │   └── ApiDiagnosticResource
            ├── ApiManagementProductResource
            │   ├── ProductApiResource
            │   ├── ProductGroupResource
            │   └── ProductPolicyResource
            ├── ApiManagementSubscriptionResource
            ├── ApiManagementPolicyResource
            ├── ApiManagementUserResource
            ├── ApiManagementGroupResource
            ├── ApiManagementBackendResource
            ├── ApiManagementGatewayResource
            ├── ApiManagementCertificateResource
            ├── ApiManagementNamedValueResource
            └── ApiManagementLoggerResource
```

## Core Workflow

### 1. Create API Management Service

```csharp
using Azure.ResourceManager.ApiManagement;
using Azure.ResourceManager.ApiManagement.Models;

// Get resource group
var resourceGroup = await subscription
    .GetResourceGroupAsync("my-resource-group");

// Define service
var serviceData = new ApiManagementServiceData(
    location: AzureLocation.EastUS,
    sku: new ApiManagementServiceSkuProperties(
        ApiManagementServiceSkuType.Developer, 
        capacity: 1),
    publisherEmail: "[email protected]",
    publisherName: "Contoso");

// Create service (long-running operation - can take 30+ minutes)
var serviceCollection = resourceGroup.Value.GetApiManagementServices();
var operation = await serviceCollection.CreateOrUpdateAsync(
    WaitUntil.Completed,
    "my-apim-service",
    serviceData);

ApiManagementServiceResource service = operation.Value;
```

### 2. Create an API

```csharp
var apiData = new ApiCreateOrUpdateContent
{
    DisplayName = "My API",
    Path = "myapi",
    Protocols = { ApiOperationInvokableProtocol.Https },
    ServiceUri = new Uri("https://backend.contoso.com/api")
};

var apiCollection = service.GetApis();
var apiOperation = await apiCollection.CreateOrUpdateAsync(
    WaitUntil.Completed,
    "my-api",
    apiData);

ApiResource api = apiOperation.Value;
```

### 3. Create a Product

```csharp
var productData = new ApiManagementProductData
{
    DisplayName = "Starter",
    Description = "Starter tier with limited access",
    IsSubscriptionRequired = true,
    IsApprovalRequired = false,
    SubscriptionsLimit = 1,
    State = ApiManagementProductState.Published
};

var productCollection = service.GetApiManagementProducts();
var productOperation = await productCollection.CreateOrUpdateAsync(
    WaitUntil.Completed,
    "starter",
    productData);

ApiManagementProductResource product = productOperation.Value;

// Add API to product
await product.GetProductApis().CreateOrUpdateAsync(
    WaitUntil.Completed,
    "my-api");
```

### 4. Create a Subscription

```csharp
var subscriptionData = new ApiManagementSubscriptionCreateOrUpdateContent
{
    DisplayName = "My Subscription",
    Scope = $"/products/{product.Data.Name}",
    State = ApiManagementSubscriptionState.Active
};

var subscriptionCollection = service.GetApiManagementSubscriptions();
var subOperation = await subscriptionCollection.CreateOrUpdateAsync(
    WaitUntil.Completed,
    "my-subscription",
    subscriptionData);

ApiManagementSubscriptionResource subscription = subOperation.Value;

// Get subscription keys
var keys = await subscription.GetSecretsAsync();
Console.WriteLine($"Primary Key: {keys.Value.PrimaryKey}");
```

### 5. Set API Policy

```csharp
var policyXml = @"
<policies>
    <inbound>
        <rate-limit calls=""100"" renewal-period=""60"" />
        <set-header name=""X-Custom-Header"" exists-action=""override"">
            <value>CustomValue</value>
        </set-header>
        <base />
    </inbound>
    <backend>
        <base />
    </backend>
    <outbound>
        <base />
    </outbound>
    <on-error>
        <base />
    </on-error>
</policies>";

var policyData = new PolicyContractData
{
    Value = policyXml,
    Format = PolicyContentFormat.Xml
};

await api.GetApiPolicy().CreateOrUpdateAsync(
    WaitUntil.Completed,
    policyData);
```

### 6. Backup and Restore

```csharp
// Backup
var backupParams = new ApiManagementServiceBackupRestoreContent(
    storageAccount: "mystorageaccount",
    containerName: "apim-backups",
    backupName: "backup-2024-01-15")
{
    AccessType = StorageAccountAccessType.SystemAssignedManagedIdentity
};

await service.BackupAsync(WaitUntil.Completed, backupParams);

// Restore
await service.RestoreAsync(WaitUntil.Completed, backupParams);
```

## Key Types Reference

| Type | Purpose |
|------|---------|
| `ArmClient` | Entry point for all ARM operations |
| `ApiManagementServiceResource` | Represents an APIM service instance |
| `ApiManagementServiceCollection` | Collection for service CRUD |
| `ApiResource` | Represents an API |
| `ApiManagementProductResource` | Represents a product |
| `ApiManagementSubscriptionResource` | Represents a subscription |
| `ApiManagementPolicyResource` | Service-level policy |
| `ApiPolicyResource` | API-level policy |
| `ApiManagementUserResource` | Represents a user |
| `ApiManagementGroupResource` | Represents a group |
| `ApiManagementBackendResource` | Represents a backend service |
| `ApiManagementGatewayResource` | Represents a self-hosted gateway |

## SKU Types

| SKU | Purpose | Capacity |
|-----|---------|----------|
| `Developer` | Development/testing (no SLA) | 1 |
| `Basic` | Entry-level production | 1-2 |
| `Standard` | Medium workloads | 1-4 |
| `Premium` | High availability, multi-region | 1-12 per region |
| `Consumption` | Serverless, pay-per-call | N/A |

## Best Practices

1. **Use `WaitUntil.Completed`** for operations that must finish before proceeding
2. **Use `WaitUntil.Started`** for long operations like service creation (30+ min)
3. **Always use `DefaultAzureCredential`** — never hardcode keys
4. **Handle `RequestFailedException`** for ARM API errors
5. **Use `CreateOrUpdateAsync`** for idempotent operations
6. **Navigate hierarchy** via `Get*` methods (e.g., `service.GetApis()`)
7. **Policy format** — Use XML format for policies; JSON is also supported
8. **Service creation** — Developer SKU is fastest for testing (~15-30 min)

## Error Handling

```csharp
using Azure;

try
{
    var operation = await serviceCollection.CreateOrUpdateAsync(
        WaitUntil.Completed, serviceName, serviceData);
}
catch (RequestFailedException ex) when (ex.Status == 409)
{
    Console.WriteLine("Service already exists");
}
catch (RequestFailedException ex) when (ex.Status == 400)
{
    Console.WriteLine($"Bad request: {ex.Message}");
}
catch (RequestFailedException ex)
{
    Console.WriteLine($"ARM Error: {ex.Status} - {ex.ErrorCode}: {ex.Message}");
}
```

## Reference Files

| File | When to Read |
|------|--------------|
| [references/service-management.md](references/service-management.md) | Service CRUD, SKUs, networking, backup/restore |
| [references/apis-operations.md](references/apis-operations.md) | APIs, operations, schemas, versioning |
| [references/products-subscriptions.md](references/products-subscriptions.md) | Products, subscriptions, access control |
| [references/policies.md](references/policies.md) | Policy XML patterns, scopes, common policies |

## Related Resources

| Resource | Purpose |
|----------|---------|
| [API Management Documentation](https://learn.microsoft.com/en-us/azure/api-management/) | Official Azure docs |
| [Policy Reference](https://learn.microsoft.com/en-us/azure/api-management/api-management-policies) | Complete policy reference |
| [SDK Reference](https://learn.microsoft.com/en-us/dotnet/api/azure.resourcemanager.apimanagement) | .NET API reference |

安装 azure-mgmt-apimanagement-dotnet

将技能文件下载并解压至你的 .claude/skills/ 目录。

下载ZIP

克隆仓库并复制技能文件到您的项目中。

git clone https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-dotnet/skills/azure-mgmt-apimanagement-dotnet # Copy SKILL.md to your .claude/skills/ directory

复制 复制
快速设置: 将技能文件夹复制到 .claude/skills/ 目录。Claude 将自动检测并使用该技能。

相关技能

base44-cli
更新时间 2026-06-29
klingai-upgrade-migration
更新时间 2026-07-03
Railway CLI Management
更新时间 2026-07-02
Verification &amp; Quality Assurance
更新时间 2026-06-29
OR