Skip to content

Make WithEndpoint update existing endpoints instead of throwing#16039

Merged
davidfowl merged 13 commits intomainfrom
davidfowl/fb
Apr 10, 2026
Merged

Make WithEndpoint update existing endpoints instead of throwing#16039
davidfowl merged 13 commits intomainfrom
davidfowl/fb

Conversation

@davidfowl
Copy link
Copy Markdown
Contributor

@davidfowl davidfowl commented Apr 10, 2026

Description

Change WithEndpoint, WithHttpEndpoint, and WithHttpsEndpoint to update an existing endpoint when one with the same name already exists, instead of throwing a DistributedApplicationException.

When updating, only non-null parameter values are applied — null parameters preserve the existing endpoint's values. This makes the API idempotent and intuitive: With* means "set this property", not "create a new thing".

Before (throws)

// AddViteApp auto-creates "http" endpoint
builder.AddViteApp("frontend", "./frontend")
    .WithHttpEndpoint(port: 3000);  // 💥 "Endpoint already exists"

After (updates)

// Just works — updates the existing "http" endpoint
builder.AddViteApp("frontend", "./frontend")
    .WithHttpEndpoint(port: 3000);  // ✅ sets host port to 3000

// Keycloak HTTPS port pinning
builder.AddKeycloak("keycloak")
    .WithHttpsEndpoint(port: 8443);  // ✅ updates existing HTTPS endpoint

Motivation

Setting a fixed host port is a common need but the previous API threw when an endpoint with the same name already existed. This came up repeatedly:

GitHub Issues:

Discord feedback:

  • "Keycloak issuer becomes random localhost port in Aspire OIDC flow"
  • "Set VITE HTTP port to fixed port instead of randomly generated"
  • "How to specify a port for a Vite app?"

The workaround was WithEndpoint("http", e => e.Port = 3000) which requires knowing the endpoint name convention.

Fixes #13807
Fixes #15873
Fixes #15854

Checklist

  • Is this feature complete?
    • Yes. Ready to ship.
    • No. Follow-up changes expected.
  • Are you including unit tests for the changes and scenario tests if relevant?
    • Yes
    • No
  • Did you add public API?
    • Yes
    • No (behavior change to existing API)
  • Does the change make any security assumptions or guarantees?
    • Yes
    • No
  • Does the change require an update in our Aspire docs?

Add WithHttpPort<T> and WithHttpsPort<T> extension methods on
IResourceBuilder<T> where T : IResourceWithEndpoints. These provide a
simple way to set the host port on existing HTTP/HTTPS endpoints without
needing to use the lower-level WithEndpoint callback API.

This addresses a common pain point where users want to pin a port for
local development (e.g., Vite apps, Keycloak OIDC flows, API gateways)
but the existing API either requires knowledge of endpoint internals or
throws when trying to re-add an endpoint that was auto-created.

Relates to #13807
Relates to #15873

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot AI review requested due to automatic review settings April 10, 2026 15:09
@github-actions
Copy link
Copy Markdown
Contributor

github-actions bot commented Apr 10, 2026

🚀 Dogfood this PR with:

⚠️ WARNING: Do not do this without first carefully reviewing the code of this PR to satisfy yourself it is safe.

curl -fsSL https://raw.githubusercontent.com/microsoft/aspire/main/eng/scripts/get-aspire-cli-pr.sh | bash -s -- 16039

Or

  • Run remotely in PowerShell:
iex "& { $(irm https://raw.githubusercontent.com/microsoft/aspire/main/eng/scripts/get-aspire-cli-pr.ps1) } 16039"

The WithHttpPort/WithHttpsPort methods are tested in the core
Aspire.Hosting.Tests project which covers the same code path.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds WithHttpPort and WithHttpsPort extension methods to make it easier to pin host ports for existing HTTP/HTTPS endpoints on resources implementing IResourceWithEndpoints, addressing common local-dev ergonomics issues (e.g., Vite apps and Keycloak).

Changes:

  • Introduces WithHttpPort(int?) / WithHttpsPort(int?) on IResourceBuilder<T> to set host ports on the "http" / "https" endpoints.
  • Adds unit tests in Aspire.Hosting.Tests covering port-setting for container endpoints.
  • Adds JavaScript hosting tests validating port-setting behavior for Vite/Node resources.
Show a summary per file
File Description
src/Aspire.Hosting/ResourceBuilderExtensions.cs Adds the new WithHttpPort / WithHttpsPort APIs and their XML docs/exports.
tests/Aspire.Hosting.Tests/WithEndpointTests.cs Adds tests for setting ports on existing container HTTP/HTTPS endpoints.
tests/Aspire.Hosting.JavaScript.Tests/ResourceCreationTests.cs Adds tests for Vite/Node resources using the new port helpers.

Copilot's findings

Comments suppressed due to low confidence (1)

src/Aspire.Hosting/ResourceBuilderExtensions.cs:1434

  • Same issue as WithHttpPort: this uses WithEndpoint("https", endpoint => ...) which will create a new endpoint by default if one isn't present. If created, the annotation will have UriScheme inferred as "tcp" (protocol-based) and only Name set to "https", so the resulting endpoint isn't actually HTTPS. This also contradicts the docs stating the endpoint must already exist.

Recommend enforcing existence (throw with guidance to call WithHttpsEndpoint first) or at least pass createIfNotExists:false and avoid creating a malformed endpoint annotation.

    [AspireExport(Description = "Sets the host port for the HTTPS endpoint")]
    public static IResourceBuilder<T> WithHttpsPort<T>(this IResourceBuilder<T> builder, int? port) where T : IResourceWithEndpoints
    {
        ArgumentNullException.ThrowIfNull(builder);

        return builder.WithEndpoint("https", endpoint =>
        {
            endpoint.Port = port;
        });
  • Files reviewed: 2/2 changed files
  • Comments generated: 2

davidfowl and others added 3 commits April 10, 2026 08:23
…e tests

- Pass createIfNotExists: false to WithEndpoint in both WithHttpPort and
  WithHttpsPort to avoid silently creating malformed endpoints when the
  target endpoint doesn't exist.
- Add negative tests verifying no endpoint is created when http/https
  endpoints are missing.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
The new [AspireExport] methods are picked up by the polyglot codegen,
updating snapshots for TypeScript, Go, Java, Python, and Rust.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Keycloak creates its HTTPS endpoint lazily, so WithHttpsPort would be
a no-op when chained directly after AddKeycloak. Replace with a
container example that accurately demonstrates the API contract.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Instead of throwing when an endpoint with the same name already exists,
update the existing endpoint with any non-null parameter values. This
makes WithHttpEndpoint/WithHttpsEndpoint idempotent and removes the
need for separate WithHttpPort/WithHttpsPort convenience methods.

This directly solves the common pain point where resources like
AddViteApp auto-create an 'http' endpoint and users cannot call
WithHttpEndpoint to configure it.

Relates to #13807
Relates to #15873

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@davidfowl davidfowl changed the title Add WithHttpPort and WithHttpsPort convenience methods Make WithEndpoint update existing endpoints instead of throwing Apr 10, 2026
davidfowl and others added 5 commits April 10, 2026 09:39
…ations

- Remove unconditional isProxied override on update path. Since the
  parameter defaults to true in the public API, we can't distinguish
  'user passed true' from 'default true', so we leave it unchanged.
- Only add EnvironmentCallbackAnnotation when env is newly configured
  (TargetPortEnvironmentVariable was null) to avoid duplicates.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
When the env parameter changes on an update (e.g., PORT -> NEW_PORT),
the callback now reads TargetPortEnvironmentVariable from the captured
annotation at evaluation time rather than closing over the string.
This ensures only the current env var name is set, not the stale one.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Both the create and update paths now call the same helper method for
configuring the endpoint environment variable callback.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- Scheme is not changed on update (by design)
- isProxied is not changed on update (can't distinguish default from explicit)
- isExternal is updated when explicitly set (nullable, so null = don't change)

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@github-actions
Copy link
Copy Markdown
Contributor

Re-running the failed jobs in the CI workflow for this pull request because 1 job was identified as retry-safe transient failures in the CI run attempt.
GitHub was asked to rerun all failed jobs for that attempt, and the rerun is being tracked in the rerun attempt.
The job links below point to the failed attempt jobs that matched the retry-safe transient failure rules.

Since the default is true, passing false is always intentional and safe
to apply. Passing true is indistinguishable from the default so it's
left as a no-op to avoid accidentally overwriting an explicit false.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Move the EndpointAnnotation construction after the existing-endpoint
check so we don't allocate an annotation only to throw it away on the
update path. Resolve the endpoint name inline using the same logic as
the EndpointAnnotation constructor.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@github-actions
Copy link
Copy Markdown
Contributor

🎬 CLI E2E Test Recordings — 58 recordings uploaded (commit a3373a0)

View recordings
Test Recording
AddPackageInteractiveWhileAppHostRunningDetached ▶️ View Recording
AddPackageWhileAppHostRunningDetached ▶️ View Recording
AgentCommands_AllHelpOutputs_AreCorrect ▶️ View Recording
AgentInitCommand_DefaultSelection_InstallsSkillOnly ▶️ View Recording
AgentInitCommand_MigratesDeprecatedConfig ▶️ View Recording
AllPublishMethodsBuildDockerImages ▶️ View Recording
AspireAddPackageVersionToDirectoryPackagesProps ▶️ View Recording
AspireUpdateRemovesAppHostPackageVersionFromDirectoryPackagesProps ▶️ View Recording
Banner_DisplayedOnFirstRun ▶️ View Recording
Banner_DisplayedWithExplicitFlag ▶️ View Recording
Banner_NotDisplayedWithNoLogoFlag ▶️ View Recording
CertificatesClean_RemovesCertificates ▶️ View Recording
CertificatesTrust_WithNoCert_CreatesAndTrustsCertificate ▶️ View Recording
CertificatesTrust_WithUntrustedCert_TrustsCertificate ▶️ View Recording
ConfigSetGet_CreatesNestedJsonFormat ▶️ View Recording
CreateAndRunAspireStarterProject ▶️ View Recording
CreateAndRunAspireStarterProjectWithBundle ▶️ View Recording
CreateAndRunEmptyAppHostProject ▶️ View Recording
CreateAndRunJavaEmptyAppHostProject ▶️ View Recording
CreateAndRunJsReactProject ▶️ View Recording
CreateAndRunPythonReactProject ▶️ View Recording
CreateAndRunTypeScriptEmptyAppHostProject ▶️ View Recording
CreateAndRunTypeScriptStarterProject ▶️ View Recording
CreateJavaAppHostWithViteApp ▶️ View Recording
CreateStartAndStopAspireProject ▶️ View Recording
CreateTypeScriptAppHostWithViteApp ▶️ View Recording
DashboardRunWithOtelTracesReturnsNoTraces ▶️ View Recording
DescribeCommandResolvesReplicaNames ▶️ View Recording
DescribeCommandShowsRunningResources ▶️ View Recording
DetachFormatJsonProducesValidJson ▶️ View Recording
DoctorCommand_DetectsDeprecatedAgentConfig ▶️ View Recording
DoctorCommand_WithSslCertDir_ShowsTrusted ▶️ View Recording
DoctorCommand_WithoutSslCertDir_ShowsPartiallyTrusted ▶️ View Recording
GlobalMigration_HandlesCommentsAndTrailingCommas ▶️ View Recording
GlobalMigration_HandlesMalformedLegacyJson ▶️ View Recording
GlobalMigration_PreservesAllValueTypes ▶️ View Recording
GlobalMigration_SkipsWhenNewConfigExists ▶️ View Recording
GlobalSettings_MigratedFromLegacyFormat ▶️ View Recording
InitTypeScriptAppHost_AugmentsExistingViteRepoAtRoot ▶️ View Recording
InvalidAppHostPathWithComments_IsHealedOnRun ▶️ View Recording
LegacySettingsMigration_AdjustsRelativeAppHostPath ▶️ View Recording
LogsCommandShowsResourceLogs ▶️ View Recording
PsCommandListsRunningAppHost ▶️ View Recording
PsFormatJsonOutputsOnlyJsonToStdout ▶️ View Recording
PublishWithDockerComposeServiceCallbackSucceeds ▶️ View Recording
RestoreGeneratesSdkFiles ▶️ View Recording
RestoreSupportsConfigOnlyHelperPackageAndCrossPackageTypes ▶️ View Recording
RunFromParentDirectory_UsesExistingConfigNearAppHost ▶️ View Recording
SecretCrudOnDotNetAppHost ▶️ View Recording
SecretCrudOnTypeScriptAppHost ▶️ View Recording
StagingChannel_ConfigureAndVerifySettings_ThenSwitchChannels ▶️ View Recording
StartAndWaitForTypeScriptSqlServerAppHostWithNativeAssets ▶️ View Recording
StopAllAppHostsFromAppHostDirectory ▶️ View Recording
StopAllAppHostsFromUnrelatedDirectory ▶️ View Recording
StopNonInteractiveMultipleAppHostsShowsError ▶️ View Recording
StopNonInteractiveSingleAppHost ▶️ View Recording
StopWithNoRunningAppHostExitsSuccessfully ▶️ View Recording
UnAwaitedChainsCompileWithAutoResolvePromises ▶️ View Recording

📹 Recordings uploaded automatically from CI run #24268589828

@davidfowl davidfowl merged commit cf23e00 into main Apr 10, 2026
269 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

5 participants