Skip to content

Preserve WebApplicationFactory Kestrel port precedence - #70520

Merged
BrennanConroy merged 6 commits into
mainfrom
pr/67714/brennanconroy-investigate-test-failure
Nov 12, 2026
Merged

BrennanConroy merged 6 commits into
mainfrom
pr/67714/brennanconroy-investigate-test-failure

Conversation

@BrennanConroy

Copy link
Copy Markdown
Member

Preserve WebApplicationFactory Kestrel port precedence

  • You've read the Contributor Guide and Code of Conduct.
  • You've included unit or integration tests for your change, where applicable.
  • You've included inline docs for your change, where applicable.
  • There's an open issue for the PR that you are making. If you'd like to propose a new feature or change, please open an issue to discuss the change or find an existing issue.

Preserve Kestrel port precedence during startup

Description

Follow-up to #67714. Apply the requested WebApplicationFactory.UseKestrel(port) address in a startup filter before Kestrel binds. This preserves its precedence over configured Kestrel endpoints and preferred hosting URLs, including when a Kestrel options callback is provided, without reintroducing the post-build startup race. Add real-server regression coverage for these scenarios and minimal hosting.

Validation

. .\activate.ps1
$env:ASPNETCORE_TEST_LOG_MAXPATH='32767'
dotnet test .\src\Mvc\test\Mvc.FunctionalTests\Microsoft.AspNetCore.Mvc.FunctionalTests.csproj --no-restore -p:NuGetAudit=false -p:UseIisNativeAssets=false --filter 'FullyQualifiedName~RealServerPortOverrideTests|FullyQualifiedName~RealServerUsingMinimalBackedIntegrationTests|FullyQualifiedName~RealServerWithCustomConfigurationIntegrationTests|FullyQualifiedName~RealServerWithDynamicPortIntegrationTests|FullyQualifiedName~RealServerWithSpecifiedPortBackedIntegrationTests' -v:q

Passed: 12, Failed: 0, Skipped: 0.

Related to #67340 (closed).

BrennanConroy and others added 6 commits July 9, 2026 13:28
Configure the Kestrel endpoint via KestrelServerOptions.Listen instead of
mutating IServerAddressesFeature.Addresses after the host is built. For
minimal/WebApplication apps run via DeferredHostBuilder, the app starts
Kestrel on its own thread, which can make the addresses collection read-only
before the factory could update it, causing an intermittent
InvalidOperationException ("IServerAddressesFeature.Addresses cannot be
modified after the server has started").

Also un-quarantines
RealServerUsingMinimalBackedIntegrationTests.CanResolveServices, whose root
cause is this same race.

Co-authored-by: Copilot App <[email protected]>
Copilot AI balanced review requested due to automatic review settings November 11, 2026 21:59
@github-actions github-actions Bot added the area-mvc Includes: MVC, Actions and Controllers, Localization, CORS, most templates label Nov 11, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

Startup.Configure can overwrite the requested UseKestrel(port) address, causing Kestrel to bind the application's port instead of the requested port.

1 open issue
What changed in this PR

This follow-up to #67714 restores WebApplicationFactory.UseKestrel(port) precedence while avoiding the post-build address mutation that caused startup races.

Changes:

  • Applies the requested address through a startup filter before Kestrel binds, including when an options callback is supplied.
  • Adds real-server coverage for configured endpoints, preferred URLs, duplicate listeners, minimal hosting, and short-circuiting startup filters.
  • Adds the HTTP abstractions reference needed by the startup filter.
File Description
src/​Mvc/​test/​Mvc.FunctionalTests/​RealServerPortOverrideTests.cs Adds six port-precedence regression tests.
src/​Mvc/​Mvc.Testing/​src/​WebApplicationFactory.cs Moves port selection into a startup filter that sets the preferred server address.
src/​Mvc/​Mvc.Testing/​src/​Microsoft.AspNetCore.Mvc.Testing.csproj References HTTP abstractions for IApplicationBuilder.

Review effort: Balanced

Comment on lines +240 to +260
services.AddSingleton<IStartupFilter>(serviceProvider => new ServerPortStartupFilter(serviceProvider.GetRequiredService<IServer>(), port));
});
}
}

private sealed class ServerPortStartupFilter(IServer server, int port) : IStartupFilter
{
public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next)
{
// Configure addresses during the app's startup, before Kestrel binds, including
// when a minimal app starts on its own thread.
var serverAddressFeature = server.Features.Get<IServerAddressesFeature>();
if (serverAddressFeature is not null)
{
serverAddressFeature.Addresses.Clear();
serverAddressFeature.Addresses.Add($"http://127.0.0.1:{port}");
serverAddressFeature.PreferHostingUrls = true;
}

return next;
}
@PureWeen

Copy link
Copy Markdown
Member

/review

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Source-only review of frozen head 6a5f374a9b5dac24ce60181c14f833adf08904f8 found one validated P2 regression: the new startup-filter-only port override is skipped when legacy startup service initialization fails under CaptureStartupErrors(true), so the captured error application can bind an application-configured URL instead of the UseKestrel(int) port.

Existing-feedback coverage: discussion #discussion_r4543708222 separately identifies that Startup.Configure can replace the address after this filter's composition-time mutation; it was not republished. No unresolved candidates remain. The routed docs/CrossCuttingGuidance.md review completed all in-scope source checks; execution of PR code, tests, CI, browser workflows, and samples was excluded, as was security assessment. No materially changed area lacked routed guidance.

Provenance: immutable head 6a5f374a9b5dac24ce60181c14f833adf08904f8, merge base 60ef0101bf97cfccb49ede034b38659c15474d1b, base tip and trusted guidance commit d8754d1fc8751b5a8ee7e8d0d28df4052cf63e77. Proof is frozen-source-only; no target code or tests were executed. Tracked Git bytes only were available, with symlinks, submodules, and LFS targets outside the evidence boundary.

Generated by ASP.NET Core Pull Request Review for #70520 · copilot · gpt56 · 130 AIC · ⌖ 12.6 AIC · ⊞ 18.8K
Comment /review to run again

{
builder.ConfigureServices(services =>
{
services.AddSingleton<IStartupFilter>(serviceProvider => new ServerPortStartupFilter(serviceProvider.GetRequiredService<IServer>(), port));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 — Preserve the requested port when startup errors are captured

With a legacy IWebHostBuilder, CaptureStartupErrors(true), and a Startup.ConfigureServices exception, WebHost.BuildApplication rethrows the captured exception before startup filters are resolved. The error-page path then copies the application's configured URLs and starts Kestrel, so this filter never applies the port supplied to UseKestrel(int). The previous implementation configured options.Listen(..., port) before startup and therefore retained the requested endpoint on this path.

A minimal repro is a legacy startup whose ConfigureServices throws, with UseUrls("(127.0.0.1/redacted) followed by factory.UseKestrel(0)andfactory.CreateClient()`; the new path attempts port 1 instead of selecting a dynamic loopback port. Please apply the override from a pre-server-start hook that also runs for the captured-error application, while retaining the successful-startup precedence behavior.

@BrennanConroy
BrennanConroy merged commit 034cdd3 into main Nov 12, 2026
31 checks passed
@BrennanConroy
BrennanConroy deleted the pr/67714/brennanconroy-investigate-test-failure branch November 12, 2026 19:33
@github-actions

Copy link
Copy Markdown
Contributor

✅ No documentation PR was created.

Confidence that documentation is needed: 15%

No docs needed: bug fix restoring intended behavior, with tests.

Documentation surfaces considered

  • Conceptual article: Not required — Bug fix to startup port precedence in WebApplicationFactory; no new public API, and no existing docs cover UseKestrel(port).
  • Migration guidance: Not required — No action needed by users upgrading.
  • Breaking change: Not required — Restores intended precedence from a prior change; no concrete compatibility break.

This branch was previously deployed

1 inactive deployment
copilot-pat-pool — 6a5f374a Deployed Nov 12, 2026 by BrennanConroy via conclusion #312
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-mvc Includes: MVC, Actions and Controllers, Localization, CORS, most templates

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants