Azure Mgmt Apicenter Dotnet

作者 microsoft354361d83247MIT收錄於 2026年10月8日更新於 2026年10月8日

Azure API Center SDK for .NET. Centralized API inventory management with governance, versioning, and discovery. Use for creating API services, workspaces, APIs, versions, definitions, environments, deployments, and metadata schemas. Triggers: "API Center", "ApiCenterService", "ApiCenterWorkspace", "ApiCenterApi", "API inventory", "API governance", "API versioning", "API catalog", "API discovery".

AI 產生的概覽

指導 .NET 開發人員使用 Azure API Center SDK 管理 API 清單、版本、定義、環境與部署。

功能
此技能提供使用 Azure.ResourceManager.ApiCenter .NET SDK 的 C# 程式碼範例與指引。內容涵蓋建立與管理 API Center 服務、工作區、API、版本、定義、環境、部署以及中繼資料結構描述。同時說明如何匯入與匯出 OpenAPI 規格、列出與搜尋 API,以及處理常見的 Azure 錯誤。
適用情境
適用於建置管理 Azure API Center 清單的 .NET 應用程式或自動化工作。適合註冊 API、上傳 OpenAPI 規格、追蹤生命週期階段、定義治理中繼資料,以及將 API 連結至部署環境等情境。
執行需求
需要 .NET SDK 以及 Azure.ResourceManager.ApiCenter 與 Azure.Identity NuGet 套件。需要 Azure 訂用帳戶、資源群組、API Center 服務名稱,以及適當的認證(DefaultAzureCredential 或 ManagedIdentityCredential 等特定認證)。需要連線至 Azure 的網路存取。不包含指令碼,僅為指示與程式碼範例。

Azure.ResourceManager.ApiCenter (.NET)

Centralized API inventory and governance SDK for managing APIs across your organization.

Installation

bash
dotnet add package Azure.ResourceManager.ApiCenterdotnet add package Azure.Identity

Current Version: v1.0.0 (GA)
API Version: 2024-03-01

Environment Variables

bash
AZURE_SUBSCRIPTION_ID=<your-subscription-id>  # Required: Azure subscription IDAZURE_RESOURCE_GROUP=<your-resource-group>  # Required: resource group nameAZURE_APICENTER_SERVICE_NAME=<your-apicenter-service>  # Required: API Center service nameAZURE_TOKEN_CREDENTIALS=prod  # Required only if DefaultAzureCredential is used in production

Authentication

csharp
using Azure.Identity;using Azure.ResourceManager;using Azure.ResourceManager.ApiCenter;
// 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();ArmClient client = new ArmClient(credential);

Resource Hierarchy

Subscription└── ResourceGroup    └── ApiCenterService                    # API inventory service        ├── Workspace                       # Logical grouping of APIs        │   ├── Api                         # API definition        │   │   └── ApiVersion              # Version of the API        │   │       └── ApiDefinition       # OpenAPI/GraphQL/etc specification        │   ├── Environment                 # Deployment target (dev/staging/prod)        │   └── Deployment                  # API deployed to environment        └── MetadataSchema                  # Custom metadata definitions

Core Workflows

1. Create API Center Service

csharp
using Azure.ResourceManager.ApiCenter;using Azure.ResourceManager.ApiCenter.Models;
ResourceGroupResource resourceGroup = await client    .GetDefaultSubscriptionAsync()    .Result    .GetResourceGroupAsync("my-resource-group");
ApiCenterServiceCollection services = resourceGroup.GetApiCenterServices();
ApiCenterServiceData data = new ApiCenterServiceData(AzureLocation.EastUS){    Identity = new ManagedServiceIdentity(ManagedServiceIdentityType.SystemAssigned)};
ArmOperation<ApiCenterServiceResource> operation = await services    .CreateOrUpdateAsync(WaitUntil.Completed, "my-api-center", data);
ApiCenterServiceResource service = operation.Value;

2. Create Workspace

csharp
ApiCenterWorkspaceCollection workspaces = service.GetApiCenterWorkspaces();
ApiCenterWorkspaceData workspaceData = new ApiCenterWorkspaceData{    Title = "Engineering APIs",    Description = "APIs owned by the engineering team"};
ArmOperation<ApiCenterWorkspaceResource> operation = await workspaces    .CreateOrUpdateAsync(WaitUntil.Completed, "engineering", workspaceData);
ApiCenterWorkspaceResource workspace = operation.Value;

3. Create API

csharp
ApiCenterApiCollection apis = workspace.GetApiCenterApis();
ApiCenterApiData apiData = new ApiCenterApiData{    Title = "Orders API",    Description = "API for managing customer orders",    Kind = ApiKind.Rest,    LifecycleStage = ApiLifecycleStage.Production,    TermsOfService = new ApiTermsOfService    {        Uri = new Uri("https://example.com/terms")    },    ExternalDocumentation =     {        new ApiExternalDocumentation        {            Title = "Documentation",            Uri = new Uri("https://docs.example.com/orders")        }    },    Contacts =    {        new ApiContact        {            Name = "API Support",            Email = "[email protected]"        }    }};
// Add custom metadataapiData.CustomProperties = BinaryData.FromObjectAsJson(new{    team = "orders-team",    costCenter = "CC-1234"});
ArmOperation<ApiCenterApiResource> operation = await apis    .CreateOrUpdateAsync(WaitUntil.Completed, "orders-api", apiData);
ApiCenterApiResource api = operation.Value;

4. Create API Version

csharp
ApiCenterApiVersionCollection versions = api.GetApiCenterApiVersions();
ApiCenterApiVersionData versionData = new ApiCenterApiVersionData{    Title = "v1.0.0",    LifecycleStage = ApiLifecycleStage.Production};
ArmOperation<ApiCenterApiVersionResource> operation = await versions    .CreateOrUpdateAsync(WaitUntil.Completed, "v1-0-0", versionData);
ApiCenterApiVersionResource version = operation.Value;

5. Create API Definition (Upload OpenAPI Spec)

csharp
ApiCenterApiDefinitionCollection definitions = version.GetApiCenterApiDefinitions();
ApiCenterApiDefinitionData definitionData = new ApiCenterApiDefinitionData{    Title = "OpenAPI Specification",    Description = "Orders API OpenAPI 3.0 definition"};
ArmOperation<ApiCenterApiDefinitionResource> operation = await definitions    .CreateOrUpdateAsync(WaitUntil.Completed, "openapi", definitionData);
ApiCenterApiDefinitionResource definition = operation.Value;
// Import specificationstring openApiSpec = await File.ReadAllTextAsync("orders-api.yaml");
ApiSpecImportContent importContent = new ApiSpecImportContent{    Format = ApiSpecImportSourceFormat.Inline,    Value = openApiSpec,    Specification = new ApiSpecImportSpecification    {        Name = "openapi",        Version = "3.0.1"    }};
await definition.ImportSpecificationAsync(WaitUntil.Completed, importContent);

6. Export API Specification

csharp
ApiCenterApiDefinitionResource definition = await client    .GetApiCenterApiDefinitionResource(definitionResourceId)    .GetAsync();
ArmOperation<ApiSpecExportResult> operation = await definition    .ExportSpecificationAsync(WaitUntil.Completed);
ApiSpecExportResult result = operation.Value;
// result.Format - e.g., "inline"// result.Value - the specification content

7. Create Environment

csharp
ApiCenterEnvironmentCollection environments = workspace.GetApiCenterEnvironments();
ApiCenterEnvironmentData envData = new ApiCenterEnvironmentData{    Title = "Production",    Description = "Production environment",    Kind = ApiCenterEnvironmentKind.Production,    Server = new ApiCenterEnvironmentServer    {        ManagementPortalUris = { new Uri("https://portal.azure.com") }    },    Onboarding = new EnvironmentOnboardingModel    {        Instructions = "Contact platform team for access",        DeveloperPortalUris = { new Uri("https://developer.example.com") }    }};
ArmOperation<ApiCenterEnvironmentResource> operation = await environments    .CreateOrUpdateAsync(WaitUntil.Completed, "production", envData);

8. Create Deployment

csharp
ApiCenterDeploymentCollection deployments = workspace.GetApiCenterDeployments();
// Get environment resource IDResourceIdentifier envResourceId = ApiCenterEnvironmentResource.CreateResourceIdentifier(    subscriptionId, resourceGroupName, serviceName, workspaceName, "production");
// Get API definition resource IDResourceIdentifier definitionResourceId = ApiCenterApiDefinitionResource.CreateResourceIdentifier(    subscriptionId, resourceGroupName, serviceName, workspaceName,     "orders-api", "v1-0-0", "openapi");
ApiCenterDeploymentData deploymentData = new ApiCenterDeploymentData{    Title = "Orders API - Production",    Description = "Production deployment of Orders API v1.0.0",    EnvironmentId = envResourceId,    DefinitionId = definitionResourceId,    State = ApiCenterDeploymentState.Active,    Server = new ApiCenterDeploymentServer    {        RuntimeUris = { new Uri("https://api.example.com/orders") }    }};
ArmOperation<ApiCenterDeploymentResource> operation = await deployments    .CreateOrUpdateAsync(WaitUntil.Completed, "orders-api-prod", deploymentData);

9. Create Metadata Schema

csharp
ApiCenterMetadataSchemaCollection schemas = service.GetApiCenterMetadataSchemas();
string jsonSchema = """{    "type": "object",    "properties": {        "team": {            "type": "string",            "title": "Owning Team"        },        "costCenter": {            "type": "string",            "title": "Cost Center"        },        "dataClassification": {            "type": "string",            "enum": ["public", "internal", "confidential"],            "title": "Data Classification"        }    },    "required": ["team"]}""";
ApiCenterMetadataSchemaData schemaData = new ApiCenterMetadataSchemaData{    Schema = jsonSchema,    AssignedTo =    {        new MetadataAssignment        {            Entity = MetadataAssignmentEntity.Api,            Required = true        }    }};
ArmOperation<ApiCenterMetadataSchemaResource> operation = await schemas    .CreateOrUpdateAsync(WaitUntil.Completed, "api-metadata", schemaData);

10. List and Search APIs

csharp
// List all APIs in a workspaceApiCenterWorkspaceResource workspace = await client    .GetApiCenterWorkspaceResource(workspaceResourceId)    .GetAsync();
await foreach (ApiCenterApiResource api in workspace.GetApiCenterApis()){    Console.WriteLine($"API: {api.Data.Title}");    Console.WriteLine($"  Kind: {api.Data.Kind}");    Console.WriteLine($"  Stage: {api.Data.LifecycleStage}");        // List versions    await foreach (ApiCenterApiVersionResource version in api.GetApiCenterApiVersions())    {        Console.WriteLine($"  Version: {version.Data.Title}");    }}
// List environmentsawait foreach (ApiCenterEnvironmentResource env in workspace.GetApiCenterEnvironments()){    Console.WriteLine($"Environment: {env.Data.Title} ({env.Data.Kind})");}
// List deploymentsawait foreach (ApiCenterDeploymentResource deployment in workspace.GetApiCenterDeployments()){    Console.WriteLine($"Deployment: {deployment.Data.Title}");    Console.WriteLine($"  State: {deployment.Data.State}");}

Key Types Reference

TypePurpose
ApiCenterServiceResourceAPI Center service instance
ApiCenterWorkspaceResourceLogical grouping of APIs
ApiCenterApiResourceIndividual API
ApiCenterApiVersionResourceVersion of an API
ApiCenterApiDefinitionResourceAPI specification (OpenAPI, etc.)
ApiCenterEnvironmentResourceDeployment environment
ApiCenterDeploymentResourceAPI deployment to environment
ApiCenterMetadataSchemaResourceCustom metadata schema
ApiKindrest, graphql, grpc, soap, webhook, websocket, mcp
ApiLifecycleStagedesign, development, testing, preview, production, deprecated, retired
ApiCenterEnvironmentKinddevelopment, testing, staging, production
ApiCenterDeploymentStateactive, inactive

Best Practices

  1. Organize with workspaces — Group APIs by team, domain, or product
  2. Use metadata schemas — Define custom properties for governance
  3. Track lifecycle stages — Keep API status current (design → production → deprecated)
  4. Document environments — Include onboarding instructions and portal URIs
  5. Version consistently — Use semantic versioning for API versions
  6. Import specifications — Upload OpenAPI/GraphQL specs for discovery
  7. Link deployments — Connect APIs to their runtime environments
  8. Use managed identity — Enable SystemAssigned identity for secure integrations

Error Handling

csharp
using Azure;
try{    ArmOperation<ApiCenterApiResource> operation = await apis        .CreateOrUpdateAsync(WaitUntil.Completed, "my-api", apiData);}catch (RequestFailedException ex) when (ex.Status == 409){    Console.WriteLine("API already exists with conflicting configuration");}catch (RequestFailedException ex) when (ex.Status == 400){    Console.WriteLine($"Invalid request: {ex.Message}");}catch (RequestFailedException ex){    Console.WriteLine($"Azure error: {ex.Status} - {ex.Message}");}

Related SDKs

SDKPurposeInstall
Azure.ResourceManager.ApiCenterAPI Center management (this SDK)dotnet add package Azure.ResourceManager.ApiCenter
Azure.ResourceManager.ApiManagementAPI gateway and policiesdotnet add package Azure.ResourceManager.ApiManagement

Reference Links

來源與署名

來源:microsoft/skills位於.github/plugins/azure-sdk-dotnet/skills/azure-mgmt-apicenter-dotnet提交354361d

授權條款: MIT

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

檢舉或申請下架