
关于
Azure 资源管理器 .NET SDK,用于 API 管理服务。
name: azure-mgmt-apimanagement-dotnet description: 用于 .NET 的 Azure API 管理资源管理器 SDK。 risk: unknown source: community date_added: '2026-02-27'
Azure.ResourceManager.ApiManagement (.NET)
用于通过 Azure Resource Manager 配置和管理 Azure API 管理资源的管理平面 SDK。
⚠️ 管理平面 vs 数据平面
- 此 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>
# 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;
// Always use DefaultAzureCredential
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 管理服务
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: "admin@contoso.com",
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.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. 创建订阅
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. 设置策略
// Rate limiting policy at API level
var policyXml = @"
<policies>
<inbound>
<rate-limit calls=""100"" renewal-period=""60"" />
<set-header name=""X-Custom"" exists-action=""override"">
<value>managed</value>
</set-header>
</inbound>
</policies>";
var policyData = new PolicyContractData
{
Value = policyXml,
Format = PolicyContentFormat.Xml
};
await api.GetApiPolicy().CreateOrUpdateAsync(
WaitUntil.Completed,
policyData);
常见模式
列出所有 API
await foreach (var api in service.GetApis().GetAllAsync())
{
Console.WriteLine($"{api.Data.DisplayName} - {api.Data.Path}");
}
导入 OpenAPI 规范
var importData = new ApiCreateOrUpdateContent
{
DisplayName = "Petstore API",
Path = "petstore",
Protocols = { ApiOperationInvokableProtocol.Https },
Format = ContentFormat.OpenApiJson,
Value = File.ReadAllText("petstore.json"),
ServiceUri = new Uri("https://petstore.swagger.io/v2")
};
await service.GetApis().CreateOrUpdateAsync(
WaitUntil.Completed,
"petstore-api",
importData);
管理后端
var backendData = new ApiManagementBackendData
{
Uri = new Uri("https://my-backend.azurewebsites.net"),
Protocol = BackendProtocol.Http,
Description = "My App Service backend"
};
await service.GetApiManagementBackends().CreateOrUpdateAsync(
WaitUntil.Completed,
"my-backend",
backendData);
错误处理
try
{
var result = await serviceCollection.CreateOrUpdateAsync(
WaitUntil.Completed, serviceName, serviceData);
}
catch (RequestFailedException ex) when (ex.Status == 409)
{
// Service already exists - get existing
var existing = await serviceCollection.GetAsync(serviceName);
}
catch (RequestFailedException ex)
{
Console.WriteLine($"Error {ex.Status}: {ex.Message}");
Console.WriteLine($"Error Code: {ex.ErrorCode}");
}
重要注意事项
- 服务创建可能需要 30-45 分钟(使用
WaitUntil.Completed) - 始终使用
DefaultAzureCredential以获得灵活的认证方式 - 资源名称必须全局唯一(
{name}.azure-api.net) - 开发者 SKU 适用于非生产环境(无 SLA)
- 策略使用 XML 格式,遵循入站/后端/出站/错误处理流程
- 使用
WaitUntil.Started进行异步操作(不等待完成)
兼容工具
Claude CodeCursor
标签
后端开发
