Repository navigation
Preserve WebApplicationFactory Kestrel port precedence - #70520
Conversation
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]>
Co-authored-by: Copilot App <[email protected]>
Co-authored-by: Copilot App <[email protected]>
Co-authored-by: Copilot App <[email protected]>
There was a problem hiding this comment.
🟡 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
| 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; | ||
| } |
|
/review |
There was a problem hiding this comment.
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)); |
There was a problem hiding this comment.
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.
|
✅ No documentation PR was created. Confidence that documentation is needed: 15% No docs needed: bug fix restoring intended behavior, with tests. Documentation surfaces considered
|

Preserve WebApplicationFactory Kestrel port precedence
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
Passed: 12, Failed: 0, Skipped: 0.
Related to #67340 (closed).