Ports Fall Silent In ASP.NET Core WebApp Factories

by Jule 51 views
Ports Fall Silent In ASP.NET Core WebApp Factories

WebApplicationFactory.UseKestrel(int port) sets the port correctly on base factories but ignores it when used via WithWebHostBuilder - Kestrel defaults to 5000 instead. This hidden glitch surfaces in integration tests where dynamic porting fails despite explicit calls. The root? The parent factory’s CreateHost delegates control, overriding child port settings via TryConfigureServerPort, which reads a parent-level _kestrelPort that’s null on derived builds. The workaround? Subclass and override ConfigureWebHost - this captures the subclass’s port directly, bypassing parent delegation. When should you worry? If your test suite relies on precise porting for API integration or local development, this bug breaks consistency. Don’t assume UseKestrel(port) works everywhere - context matters. Use the subclass method when fine-grained port control is essential.