Skip to content

Preserve WebApplicationFactory ports for captured startup errors - #70680

Merged
PureWeen merged 1 commit into
dotnet:mainfrom
PureWeen:shneuvil-microsoft-validate-70520-kestrel-port-fix
Nov 18, 2026
Merged

PureWeen merged 1 commit into
dotnet:mainfrom
PureWeen:shneuvil-microsoft-validate-70520-kestrel-port-fix

Conversation

@PureWeen

Copy link
Copy Markdown
Member

Preserve WebApplicationFactory ports for captured startup errors

  • 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.

Honor Kestrel port overrides when legacy startup services fail

Description

With a legacy IWebHostBuilder, CaptureStartupErrors(true), and an exception in Startup.ConfigureServices, the host skips startup filters but still starts Kestrel to serve the startup error page. Since the factory's port override is applied by a startup filter, factory.UseKestrel(0) is ignored on this path. Kestrel instead attempts to bind the application's configured URL, which can fail if that port is already in use.

Apply the requested port after building the legacy web host and before starting it. Keep the existing startup filter for generic and minimal hosts, reusing the address configuration logic without restoring the minimal-hosting startup race.

Add RealServerPortOverrideTests.PortOverrideIsAppliedWhenStartupServicesThrow. The test keeps the application's configured port occupied, throws from the real startup services path, and verifies that the factory serves the original startup error over HTTP on a different dynamic loopback port.

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 -p:BuildNodeJS=false -p:StaticWebAssetsEnabled=false --filter 'FullyQualifiedName~RealServer' -v:q

Passed: 16, failed: 0, skipped: 0.

Before the fix, the new regression fails with the expected occupied-port bind error; the six existing port-override tests pass. The same regression passes using the exact factory source from before #67714 and from after #67714 / before #70520, compiled against the remaining current source graph.

Validation covers real Kestrel sockets, legacy startup-error handling, generic/minimal hosting, and existing port-precedence scenarios. JavaScript/static assets and IIS native assets are disabled for this focused managed HTTP run; browser/IIS behavior and the full MVC suite were not validated.

Follow-up to #70520; historical context: #67714.

Apply the requested port before starting the legacy web host so captured startup service errors cannot bypass the override. Retain the startup filter for generic and minimal hosts, reusing the address configuration helper.

Add a real-server regression that keeps the application port occupied and checks the captured startup error is served on a dynamic loopback port.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 17, 2026 22:18
@github-actions github-actions Bot added the area-mvc Includes: MVC, Actions and Controllers, Localization, CORS, most templates label Nov 17, 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.

🟢 Approval recommended

No active review issues are reported for the legacy-host port-override change.

No open issues 🎉

What changed in this PR

Preserves WebApplicationFactory.UseKestrel(port) overrides when a legacy host captures a startup-services exception, without reintroducing the minimal-hosting startup race addressed by earlier fixes.

Changes:

  • Applies the requested address after building the legacy host and before starting it.
  • Reuses address-configuration logic while retaining the startup filter for generic and minimal hosts.
  • Adds a regression test that occupies the application’s configured port and verifies the original startup error is served over HTTP on a different dynamic loopback port.
File Description
src/​Mvc/​test/​Mvc.FunctionalTests/​RealServerPortOverrideTests.cs Adds real-server coverage for port overrides during captured startup-services failures.
src/​Mvc/​Mvc.Testing/​src/​WebApplicationFactory.cs Applies legacy-host port overrides before startup and extracts shared address configuration.

Review effort: Balanced

@kubaflo kubaflo 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.

Review summary

Reviewed 72042c1fe03750c74dae826180100626471aab69, target main, frozen base tip 6f80be5513b2f1d785d51752f9cd065c56af4c6f, verified merge base 90d90ff3574fb9b0b59838e9cebca908e6af93c5. Read both changed files in full and traced legacy WebHost initialization, startup-error recovery, address selection, factory client-address extraction, and the unchanged generic/minimal-host path. Reconciled CCR agreement 5947628803; no existing inline defect finding was present.

No actionable defect established. The source supports the reported mechanism: WebHost.Initialize retains the startup-services exception when capture is enabled; BuildApplication rethrows it before composing startup filters, then constructs the error-page application in its catch. Thus the port startup filter does not run on this path although Kestrel still starts.

The new legacy-only pre-start call gets IWebHost.ServerFeatures (which ensures the server), replaces the advertised addresses with the requested loopback port, and sets PreferHostingUrls. AddressBinder.CreateStrategy gives those nonempty preferred addresses precedence over configured endpoints. The error-page path subsequently reuses that server; it does not restore the application's URL. The generic/minimal host still uses the startup filter at the existing pre-bind seam, so the former minimal-host race fix is not replaced with a later post-start mutation. The helper extraction preserves the existing filter's behavior.

Regression-test assessment: the new test holds a real TCP listener open on the application's configured port, throws through IStartup.ConfigureServices on BasicWebSite's actual legacy builder, and requires a different bound loopback endpoint plus the original startup exception served as HTTP 500. That exercises the missing-filter producer and consumer-visible error page rather than directly testing the helper. Existing callback/URL/explicit-endpoint/minimal-host/short-circuit tests remain unchanged. The test verifies both port selection and preservation of the startup error rather than accepting a successful bind alone.

Validation limits: git diff --check 90d90ff3574fb9b0b59838e9cebca908e6af93c5 72042c1fe03750c74dae826180100626471aab69 passed. The checkout requires SDK 12.0.100-alpha.1.26557.102; local dotnet --list-sdks reports only 11.0.100. I did not substitute that SDK, restore a toolchain, or run the functional suite. The reported 16 passing tests and historical-source red/green runs remain author-reported, not independently reproduced here. No claim that sockets or HTTP behavior were empirically validated by this review.

The title/description match the implementation and distinguish managed HTTP coverage from excluded IIS/browser/full-suite work. Required Build Analysis is pending; license/cla passes. Verdict: NEEDS_DISCUSSION; safety confidence: low, for shared startup infrastructure, pending CI, and unavailable exact-SDK execution rather than a newly established defect.

GPT-6.1 Sol source/text/CLI review; no relevant supplied visual media or UI change, browser/device or model campaign, product edits, approval, request-changes event, merge, or thread resolution.

@PureWeen

Copy link
Copy Markdown
Member Author

/review

@PureWeen
PureWeen merged commit f3a4b20 into dotnet:main Nov 18, 2026
30 checks passed
@github-actions

Copy link
Copy Markdown
Contributor

✅ No documentation PR was created.

Confidence that documentation is needed: 10%

No docs needed: bug fix restoring expected port-override behavior; confident, not an insufficient-evidence case.

Documentation surfaces considered

  • Conceptual article: Not required — Bug fix in WebApplicationFactory.cs with a functional test; no public API, defaults, or documented behavior changed.
  • Migration guidance: Not required — No user action needed on upgrade.
  • Breaking change: Not required — No compatibility impact; no API or default changes.

This branch was previously deployed

1 inactive deployment
copilot-pat-pool — 72042c1f Deployed Nov 18, 2026 by PureWeen via conclusion #386
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