Aspire.Hosting.Azure.ApiManagement 17.0.0-preview.1.26567.5

Prefix Reserved
This is a prerelease version of Aspire.Hosting.Azure.ApiManagement.
dotnet add package Aspire.Hosting.Azure.ApiManagement --version 17.0.0-preview.1.26567.5
                    
NuGet\Install-Package Aspire.Hosting.Azure.ApiManagement -Version 17.0.0-preview.1.26567.5
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Aspire.Hosting.Azure.ApiManagement" Version="17.0.0-preview.1.26567.5" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Aspire.Hosting.Azure.ApiManagement" Version="17.0.0-preview.1.26567.5" />
                    
Directory.Packages.props
<PackageReference Include="Aspire.Hosting.Azure.ApiManagement" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Aspire.Hosting.Azure.ApiManagement --version 17.0.0-preview.1.26567.5
                    
#r "nuget: Aspire.Hosting.Azure.ApiManagement, 17.0.0-preview.1.26567.5"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Aspire.Hosting.Azure.ApiManagement@17.0.0-preview.1.26567.5
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Aspire.Hosting.Azure.ApiManagement&version=17.0.0-preview.1.26567.5&prerelease
                    
Install as a Cake Addin
#tool nuget:?package=Aspire.Hosting.Azure.ApiManagement&version=17.0.0-preview.1.26567.5&prerelease
                    
Install as a Cake Tool

Azure API Management hosting integration

Use this integration to model, configure, and orchestrate an Azure API Management gateway in an Aspire solution.

Getting started

Prerequisites

Add the integration

From your AppHost directory, add the Aspire.Hosting.Azure.ApiManagement integration with the Aspire CLI:

aspire add Aspire.Hosting.Azure.ApiManagement

Usage example

Then, in the AppHost, add an Azure API Management resource and route a public path to an Aspire compute resource with either C# or TypeScript:

C#

var catalog = builder.AddProject<Projects.Catalog>("catalog")
    .WithExternalHttpEndpoints();

var apim = builder.AddAzureApiManagement("apim", new()
{
    PublisherEmail = "api-owners@example.com",
    PublisherName = "Contoso APIs",
});

apim.AddApi("catalog-api", catalog, "catalog");

TypeScript

const catalog = await builder.addNodeApp("catalog", "../catalog", "server.js")
    .withExternalHttpEndpoints();

const apim = await builder.addAzureApiManagement("apim", {
    publisherEmail: "api-owners@example.com",
    publisherName: "Contoso APIs",
});

await apim.addApi("catalog-api", catalog, "catalog");

The compute-targeted AddApi overload creates an API, an APIM backend, and root and catch-all operations for supported HTTP methods that forward requests to the deployed endpoint of the target resource. Both the API suffix itself (for example, /catalog) and its descendants are forwarded. APIs require an APIM subscription key by default. Set subscriptionRequired: false only when the API should be callable without one.

Explicit operations must have unique HTTP method and URL-template combinations, including templates that differ only in parameter names. Routes reserved for generated root and catch-all operations are rejected unless an OpenAPI import is configured for the API, regardless of whether WithOpenApiDocument is called before or after AddOperation.

API Management resources are automatically omitted during aspire run. Azure compute environments do not materialize their public endpoints in run mode, and a cloud-hosted APIM instance cannot reach a backend running on localhost. Use aspire deploy to provision APIM and exercise its routing; no execution-mode guard is required around the APIM resources.

OpenAPI import

Import the OpenAPI document exposed by an Aspire compute resource:

apim.AddApi("catalog-api", catalog, "catalog")
    .WithOpenApiEndpoint("/openapi/v1.json");

Aspire resolves the target's deployed external HTTP or HTTPS endpoint and gives APIM a link to the document. The endpoint must be publicly reachable from the APIM control plane during deployment. The default document path is /openapi/v1.json.

For private backends or documents generated before deployment, import a file relative to the AppHost directory:

apim.AddApi("catalog-api", catalog, "catalog")
    .WithOpenApiDocument("../Catalog/openapi.json");

An API can use only one OpenAPI source: either WithOpenApiDocument or WithOpenApiEndpoint. Repeating the same configuration is allowed, but configuring a different source, path, endpoint name, or format throws InvalidOperationException instead of replacing the source.

JSON and YAML OpenAPI documents are inferred from the file extension. Pass AzureApiManagementOpenApiFormat.SwaggerJson explicitly for Swagger 2.0 documents. The file is read during infrastructure generation for publish/deploy, not during aspire run, so deploy-only artifacts do not need to exist for local development. Imported operations replace the generated root and catch-all proxy operations; operations added with AddOperation are still provisioned in addition to the imported operations.

Existing API Management services

Adopt an existing service while letting Aspire manage the APIs and other child resources declared in the AppHost:

var apim = builder.AddAzureApiManagement("apim", new()
{
    PublisherEmail = "api-owners@example.com",
    PublisherName = "Contoso APIs",
    Sku = AzureApiManagementSku.Premium,
}).PublishAsExisting("shared-apim", resourceGroup: "shared-infrastructure");

apim.AddApi("catalog-api", catalog, "catalog");

Aspire treats the existing service itself as read-only. It can manage declared APIs, operations, backends, pools, policies, fragments, products, subscriptions, named values, and diagnostics, but it rejects service-level virtual-network and custom-domain mutations. It does not change the service's managed identities.

Set Sku explicitly to the adopted service's actual pricing tier, even for Developer. Aspire requires this metadata to validate SKU-dependent children such as circuit breakers and OpenAI backends; it does not query or change the existing service's SKU. The Developer default applies only to new services.

APIM uses a user-assigned managed identity for backend authentication and Key Vault access. Aspire creates and attaches an identity for new services and grants its permissions through the standard Azure role-assignment pipeline. For an existing APIM service, bring an existing identity that is already attached to the service:

var identity = builder.AddAzureUserAssignedIdentity("existing-apim-identity")
    .PublishAsExisting("shared-apim-identity", resourceGroup: "shared-infrastructure");

apim.WithAzureUserAssignedIdentity(identity);

Publishing managed-identity backends or Key Vault-backed named values for an existing service throws if its identity is not configured as an existing resource. Aspire does not query Azure to verify attachment or attach an identity to an existing service; attachment remains the caller's responsibility. Existing services with only anonymous backends and literal named values do not require an existing identity.

WithAzureUserAssignedIdentity can also supply an identity for a new service, which attaches it automatically. Configure the identity before or after adding backends and named values; their inferred role assignments follow the selected identity.

Aspire uses the same identity and role-assignment path for new and existing APIM services. Role-assignment modules deploy at the target resource's scope, including other resource groups or subscriptions. Diagnostics configured on an existing APIM service still require the service and Application Insights resource to be in the same deployment resource group.

Backends and backend pools

Backends and pools are first-class resources that can be reused by APIs. The specialized Foundry adapter configures the deployment URL, managed-identity authentication, the required Cognitive Services role assignment, and an HTTP 429 circuit breaker:

var primaryFoundry = builder.AddFoundry("foundry-primary");
var primary = primaryFoundry.AddDeployment(
    "chat-primary",
    FoundryModel.OpenAI.Gpt5Mini);

var secondaryFoundry = builder.AddFoundry("foundry-secondary");
var secondary = secondaryFoundry.AddDeployment(
    "chat-secondary",
    FoundryModel.OpenAI.Gpt5Mini);

var primaryBackend = apim.AddFoundryBackend("primary-backend", primary);
var secondaryBackend = apim.AddFoundryBackend("secondary-backend", secondary);

var pool = apim.AddBackendPool("openai-pool")
    .WithBackend(primaryBackend, priority: 1, weight: 3)
    .WithBackend(secondaryBackend, priority: 1, weight: 1);

apim.AddOpenAIApi("openai-api", path: "openai")
    .WithBackend(pool);

The generated APIM backend pool uses weighted routing between healthy members at the same priority. A lower priority number is preferred; members at the next priority are used when every member in a preferred group has an open circuit. Each backend has a circuit breaker that opens on HTTP 429 and honors the Azure OpenAI Retry-After response header.

The API authenticates with APIM's user-assigned managed identity, selected explicitly by client-id in the generated policy. Aspire grants that identity the Cognitive Services OpenAI User role on Azure OpenAI accounts and the Cognitive Services User role on Foundry accounts. The deploying principal needs Microsoft.Authorization/roleAssignments/write permission on those accounts, such as through the User Access Administrator or Owner role. Backend URLs include each physical deployment name, so a request such as:

POST https://<gateway>.azure-api.net/openai/chat/completions?api-version=<version>

is forwarded to the selected account at:

POST https://<account>/openai/deployments/<deployment>/chat/completions?api-version=<version>

The same pool model works with other services. For example, two Blob Storage services can share a pool:

var primaryBlobs = builder.AddAzureStorage("storage-primary").AddBlobs("blobs-primary");
var secondaryBlobs = builder.AddAzureStorage("storage-secondary").AddBlobs("blobs-secondary");

var primaryBackend = apim.AddBlobStorageBackend("blob-primary", primaryBlobs);
var secondaryBackend = apim.AddBlobStorageBackend("blob-secondary", secondaryBlobs);
var pool = apim.AddBackendPool("blob-pool")
    .WithBackend(primaryBackend, weight: 3)
    .WithBackend(secondaryBackend);

apim.AddApi("blob-api", path: "blobs")
    .WithBackend(pool)
    .WithInboundPolicy(
        """<set-header name="x-ms-version" exists-action="override"><value>2023-11-03</value></set-header>""");

AddBlobStorageBackend grants the APIM managed identity the Storage Blob Data Reader role and configures the Storage authentication audience.

Use AddBackend as the low-level escape hatch for other services or APIM backend features:

var backend = apim.AddBackend(
    "custom-backend",
    ReferenceExpression.Create($"https://backend.example.com"),
    new AzureApiManagementBackendOptions
    {
        Protocol = AzureApiManagementBackendProtocol.Soap,
        ManagedIdentityResource = "api://backend",
        ValidateCertificateName = false,
        CircuitBreaker = new AzureApiManagementCircuitBreakerOptions
        {
            Name = "serverErrors",
            FailureCount = 3,
            FailureIntervalSeconds = 30,
            TripDurationSeconds = 60,
            StatusCodeRanges = [new(500, 599)],
        },
    });

apim.AddApi("custom-api", path: "custom")
    .WithBackend(backend);

Generic backends do not infer Azure role assignments because the required role is service-specific. Configure permissions for apim.Resource.Identity on the target resource when using managed identity.

The same generic backend and pool APIs are available in TypeScript:

import { refExpr } from "./.aspire/modules/aspire.mjs";

const primary = await apim.addBackend(
    "primary",
    refExpr`https://primary.example.com`,
    {
        options: {
            managedIdentityResource: "api://backend",
        },
    });
const secondary = await apim.addBackend(
    "secondary",
    refExpr`https://secondary.example.com`,
    {
        options: {
            managedIdentityResource: "api://backend",
        },
    });

const pool = await apim.addBackendPool("backend-pool");
await pool.addBackendPoolMember(primary, { weight: 3 });
await pool.addBackendPoolMember(secondary);

const api = await apim.addApiWithoutTarget("pooled-api", "pooled");
await api.withApiBackendPool(pool);

Policies

Append policy statements to the generated inbound section at the service, API, or operation scope:

var api = apim.AddApi("catalog-api", catalog, "catalog")
    .WithInboundPolicy("""
        <rate-limit calls="100" renewal-period="60" />
        """);

Use WithPolicy when a complete APIM policy document is required. APIM replaces the complete policy at that scope; replacing an API policy also replaces Aspire's generated backend-routing statement. WithPolicy and WithInboundPolicy cannot be combined at the same scope because doing so would silently discard one configuration.

Aspire deploys each API-level policy after that API's generated and explicitly declared operations, including any operation-level policies, to avoid overlapping those writes to the same API.

Policy fragments

Define shared policy statements once and include them at the service, API, or operation scope:

var standardHeaders = apim.AddPolicyFragment(
    "standard-headers",
    """
    <set-header name="x-powered-by" exists-action="override">
      <value>Aspire</value>
    </set-header>
    """);

apim.WithInboundPolicyFragment(standardHeaders);
catalogApi.WithInboundPolicyFragment(standardHeaders);

Aspire creates the required <fragment> document and ensures policies are deployed after their referenced fragments.

Products and subscriptions

Group APIs into a product and optionally provision a product-scoped subscription:

apim.AddProduct("catalog-product", "Catalog", new()
    {
        Description = "Catalog APIs",
        SubscriptionRequired = true,
        ApprovalRequired = false,
    })
    .WithApi(catalogApi)
    .AddSubscription("catalog-client", "Catalog client");

API Management generates the primary and secondary subscription keys. Aspire intentionally does not expose those keys as ordinary deployment outputs because they are secrets.

Product membership is provisioned using the SDK's ServiceProductApiLink resource (Microsoft.ApiManagement/service/products/apiLinks), which references the API's full resource ID.

Customize provisioning

Use ConfigureInfrastructure to customize the generated resources through the types in Azure.Provisioning.ApiManagement, such as ApiManagementService, ApiManagementApi, and ApiManagementBackend.

Named values

Named values can contain a non-secret literal, a secret Aspire parameter, or a Key Vault secret reference:

apim.AddNamedValue("region", "westus3");

var apiKey = builder.AddParameter("upstream-api-key", secret: true);
apim.AddSecretNamedValue("upstream-api-key-value", apiKey, displayName: "UpstreamApiKey");

var vault = builder.AddAzureKeyVault("vault");
apim.AddKeyVaultNamedValue(
    "shared-secret",
    vault.GetSecret("shared-secret"),
    displayName: "SharedSecret");

Key Vault references stay late-bound and use versionless secret URIs so APIM can refresh rotated values. Aspire grants APIM's user-assigned identity the Key Vault Secrets User role through the standard Azure role-assignment pipeline. The APIM deployment waits for those role assignments before consuming secrets. Custom IAzureKeyVaultResource implementations that are not Azure provisioning resources retain inline role assignments.

Application Insights diagnostics

Enable service-wide diagnostics or override the settings for an individual API:

var insights = builder.AddAzureApplicationInsights("insights");

apim.WithApplicationInsights(insights, new()
{
    SamplingPercentage = 25,
});

catalogApi.WithApplicationInsights(insights, new()
{
    SamplingPercentage = 100,
    Verbosity = AzureApiManagementDiagnosticVerbosity.Error,
});

The default diagnostic uses W3C correlation, always logs errors, emits metrics, and does not capture request or response bodies.

Custom domains and certificates

Bind a custom APIM endpoint to a PFX certificate stored as a Key Vault secret. The hostname must be a multi-label DNS name, such as api.contoso.com; single-label hosts and IP addresses are rejected:

var certificateVault = builder.AddAzureKeyVault("certificates")
    .PublishAsExisting("contoso-certificates", resourceGroup: null);

apim.WithCustomDomain(
    "api.contoso.com",
    certificateVault.GetSecret("gateway-certificate"),
    AzureApiManagementHostnameType.Proxy,
    defaultSslBinding: true);

The certificate secret URI is versionless so APIM can automatically refresh renewed certificates. Aspire grants APIM's user-assigned identity the Key Vault Certificate User role and configures the hostname to use that identity. The Consumption SKU supports one custom domain for the gateway endpoint only. Key Vaults that require APIM's system identity through the trusted-services firewall exception are not supported by this API.

TypeScript service configuration

Products, named values, policy fragments, diagnostics, and custom domains are available to polyglot AppHosts:

const insights = await builder.addAzureApplicationInsights("insights");
const vault = await builder.addAzureKeyVault("vault");
const apim = await builder.addAzureApiManagement("apim", {
    publisherEmail: "api-owners@example.com",
    publisherName: "Contoso APIs",
});

const fragment = await apim.addPolicyFragment(
    "standard-headers",
    '<set-header name="x-powered-by" exists-action="override"><value>Aspire</value></set-header>');
await apim.withInboundPolicyFragment(fragment);
await apim.withApplicationInsights(insights);
await apim.addKeyVaultNamedValue(
    "shared-secret",
    vault,
    "shared-secret");

const product = await apim.addProduct("catalog-product", "Catalog");
await product.withApi(catalogApi);
await product.addSubscription("catalog-client", "Catalog client");

SKUs and networking

Configure the tier and capacity with AzureApiManagementOptions. The integration supports Consumption, Developer, Basic, Basic v2, Standard, Standard v2, Premium, and Premium v2 capacity validation.

Classic Developer and Premium VNet injection can use an existing undelegated Aspire subnet:

var subnet = builder.AddAzureVirtualNetwork("vnet")
    .AddSubnet("apim-subnet", "10.0.0.0/24")
    .AllowInbound(port: "3443", from: "ApiManagement", protocol: SecurityRuleProtocol.Tcp)
    .AllowInbound(port: "6390", from: AzureServiceTags.AzureLoadBalancer, protocol: SecurityRuleProtocol.Tcp);

apim.WithClassicVirtualNetwork(
    subnet,
    AzureApiManagementVirtualNetworkMode.Internal);

Both v2 networking helpers add a TCP/443 allow rule for Azure Key Vault. On an existing NSG, the helper reserves a free priority ahead of outbound TCP/443 deny rules, conservatively treating service tags and address expressions as potentially overlapping. If no earlier priority is available, configuration fails rather than adding a shadowed rule. Later modeled NSG changes must preserve that allow rule and its ordering.

Standard v2 and Premium v2 outbound integration automatically delegates a dedicated subnet to Microsoft.Web/serverFarms:

var subnet = builder.AddAzureVirtualNetwork("vnet")
    .AddSubnet("apim-subnet", "10.0.0.0/24");

apim.WithVirtualNetworkIntegration(subnet);

Premium v2 injection provides private inbound and outbound access and automatically delegates its subnet to Microsoft.Web/hostingEnvironments:

var apim = builder.AddAzureApiManagement("apim", new()
{
    PublisherEmail = "api-owners@example.com",
    PublisherName = "Contoso APIs",
    Sku = AzureApiManagementSku.PremiumV2,
});

apim.WithVirtualNetworkInjection(subnet);

Both v2 configurations require a dedicated /27 or larger subnet. Aspire creates an NSG when the subnet does not already have one and adds the required outbound HTTPS rule for the AzureKeyVault service tag. Premium v2 injection must be selected when the service is created. Configure private DNS for the injected gateway hostname as described in the Azure API Management Premium v2 injection documentation.

Private Container Apps backends

Place the Container Apps environment and APIM in separate subnets of the same virtual network. Configure the Container Apps environment with an internal load balancer and APIM with classic external VNet injection:

var vnet = builder.AddAzureVirtualNetwork("vnet");
var containerAppsSubnet = vnet.AddSubnet("container-apps-subnet", "10.0.0.0/23");
var apimSubnet = vnet.AddSubnet("apim-subnet", "10.0.2.0/24")
    .AllowInbound(port: "3443", from: "ApiManagement", protocol: SecurityRuleProtocol.Tcp)
    .AllowInbound(port: "6390", from: AzureServiceTags.AzureLoadBalancer, protocol: SecurityRuleProtocol.Tcp)
    .AllowInbound(port: "443", from: AzureServiceTags.Internet, protocol: SecurityRuleProtocol.Tcp);

var environment = builder.AddAzureContainerAppEnvironment("env")
    .WithDelegatedSubnet(containerAppsSubnet)
    .WithInternalLoadBalancer(vnet);

var catalog = builder.AddProject<Projects.Catalog>("catalog")
    .WithComputeEnvironment(environment)
    .WithExternalHttpEndpoints();

apim.WithClassicVirtualNetwork(
    apimSubnet,
    AzureApiManagementVirtualNetworkMode.External);

apim.AddApi("catalog-api", catalog, "catalog");

The Network integration's WithInternalLoadBalancer gives the Container Apps environment a private VIP and creates a private DNS zone, wildcard A record, and virtual-network link for its generated default domain. Although WithExternalHttpEndpoints enables ingress outside the Container Apps environment, the environment itself has no public endpoint; APIM reaches the app over the virtual network and is the public gateway.

Classic APIM VNet injection requires an NSG on the APIM subnet. Allow inbound TCP 3443 from the ApiManagement service tag, TCP 6390 from AzureLoadBalancer, and TCP 443 from Internet when the APIM gateway remains public.

Create an inbound private endpoint for the APIM gateway with the Azure networking integration:

var vnet = builder.AddAzureVirtualNetwork("vnet");
var privateEndpointSubnet = vnet.AddSubnet("private-endpoint-subnet", "10.0.0.0/24");

privateEndpointSubnet.AddPrivateEndpoint(apim);

Aspire provisions the private endpoint and privatelink.azure-api.net DNS zone without changing the APIM service's public network access. Adding a private endpoint does not make the gateway private-only: new services retain their default public access, and existing services retain their configured access settings. To restrict gateway access to private endpoints, disable public network access separately after configuring and approving the private endpoint, as described in the Azure API Management documentation.

Private endpoints can target new or existing APIM services. They cannot be combined with classic or Premium v2 VNet injection. Consumption and Basic v2 do not support private endpoints.

Configure Azure provisioning for local development

Adding Azure resources to the Aspire application model automatically enables development-time provisioning. From your AppHost directory, set the required values:

aspire secret set Azure:SubscriptionId "<your subscription id>"
aspire secret set Azure:ResourceGroupPrefix "<prefix for the resource group>"
aspire secret set Azure:Location "<azure location>"

See Local Azure Provisioning for more details.

Additional documentation

Feedback & contributing

https://github.com/microsoft/aspire

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
17.0.0-preview.1.26567.5 0 11/18/2026