mcpField
A
azure-mgmt-apimanagement-dotnet

azure-mgmt-apimanagement-dotnet

github.com/sickn33云与 DevOps48.7k59 次安装今天更新
代码仓库

关于 azure-mgmt-apimanagement-dotnet

面向 .NET 开发者的技能,使用 Azure Resource Manager 管理平面 SDK 管理 Azure API Management,涵盖服务与 API 配置、访问控制、策略及备份恢复,并提示验证变更和权限。

主要功能

  1. 01配置 APIM 服务与 API
  2. 02管理产品和订阅
  3. 03配置服务与 API 策略
  4. 04备份和恢复服务

适用场景

  1. 01创建 API Management 服务
  2. 02设置 API 产品和订阅
  3. 03上线前审查策略变更
  4. 04规划服务备份或恢复

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/sickn33/agentic-awesome-skills --skill azure-mgmt-apimanagement-dotnet

安装后在 Claude Code 中输入/azure-mgmt-apimanagement-dotnet确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

UPSTREAM-LICENSE.txt
UPSTREAM-NOTICE.md
references/
service-management.md
apis-operations.md
products-subscriptions.md

详细介绍

捆绑的上游支持文件

支持文件位于相对于 skill 的路径中。其固定来源、许可证、哈希值和导入变更,请参阅 UPSTREAM-NOTICE.md。

支持材料可用性

此目录副本中以下路径仍不可用:

  • <support-root>/references/policies.md

请勿调用需要这些文件的步骤。使用前,请获取原始材料并审查其依赖项、许可证和影响。独立的内联步骤和捆绑的辅助工具可在用户授权范围内继续使用。

Azure.ResourceManager.ApiManagement (.NET)

用于通过 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

版本说明:示例与版本相关;应在目标项目中解析并固定受支持的 SDK 包版本,而不是将 v1.3.0 视为当前版本。

环境变量

AZURE_SUBSCRIPTION_ID=<your-subscription-id>
# For service principal auth (optional)
AZURE_TENANT_ID=<tenant-id>
AZURE_CLIENT_ID=<client-id>
AZURE_CLIENT_SECRET=<client-secret>

身份验证

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

// Choose a deliberate credential chain; managed identity is preferable in hosted production
var credential = new DefaultAzureCredential();
var armClient = new ArmClient(credential);

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

资源层级结构

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;

// 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. 创建 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.NotPublished
};

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. 创建订阅
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 apimSubscription = subOperation.Value;

// Get subscription keys
var keys = await apimSubscription.GetSecretsAsync();
// Store keys only through the approved secret store; never log them.
5. 设置 API 策略
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
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);

关键类型参考

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

SKU 类型

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

最佳实践

  1. 对必须完成后才能继续的操作使用 WaitUntil.Completed
  2. 对服务创建等耗时操作(30 分钟以上)使用 WaitUntil.Started
  3. 选择明确的生产身份——切勿将密钥硬编码;限制凭据链回退范围
  4. 处理 RequestFailedException,以应对 ARM API 错误
  5. 对幂等操作使用 CreateOrUpdateAsync
  6. 通过 Get* 方法遍历层级结构(例如,service.GetApis())
  7. 策略格式——策略使用 XML(xml/rawxml 或相应的链接格式);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)
{
    throw; // 409 is a conflict requiring diagnosis, not proof of successful existing state
}
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 文档Azure 官方文档
策略参考完整的策略参考
SDK 参考.NET API 参考

适用场景

当需要执行概述中所述的工作流或操作时,可使用此技能。

限制

  • 仅当任务明确符合上述范围时,才使用此技能。
  • 不要将输出视为环境特定验证、测试或专家审查的替代品。
  • 如果缺少必需的输入、权限、安全边界或成功标准,请停止并请求澄清。

资源变更与 SDK 限制

这些代码片段是独立示例,省略了项目设置以及特定版本的模型类型和构造函数;它们尚未针对 Azure 编译或运行。ResourceIdentifier/AzureLocation 需要 Azure.Core,WaitUntil/ETag 需要 Azure。改用这些示例前,请核实确切的 SDK 重载、必需的 ETag 以及受支持的 SKU/区域能力。409 可能表示存在其他冲突或操作正在进行,并不代表创建成功。操作启动后仍需轮询并读取配置状态。CreateOrUpdate 可能会替换现有配置,不能因为其名称听起来具有幂等性就认为它没有风险。

在预配前,确认租户、订阅、资源 ID、RBAC、成本和部署范围。完成访问审查前,请勿发布产品;仅有订阅密钥并不等同于最终用户身份,也不构成完整的 API 授权。轮换密钥时,应一次轮换一个,并在轮换期间迁移使用者并读取确认;不要立即重新生成两个密钥。删除服务、暂停订阅、更改策略和恢复操作都需要明确批准目标并制定恢复计划。使用托管标识进行备份,还需要实际的标识、存储权限和受支持的层级;备份不能保证完整回滚。策略示例未添加 JWT 验证,其速率限制也不是普遍适用的流量上限。保留现有策略继承,并在推出前使用经过审查的修订版本。请勿在公开日志中包含原始 ARM 错误正文。

评论

支持 Markdown