Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 10 additions & 17 deletions src/Mvc/Mvc.Testing/src/WebApplicationFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Text.Json;
Expand Down Expand Up @@ -216,33 +217,26 @@ private IWebHost CreateKestrelServer(IWebHostBuilder builder)

var host = builder.Build();

TryConfigureServerPort(() => GetServerAddressFeature(host));

host.Start();
return host;
}
#pragma warning restore ASPDEPR008 // IWebHost is obsolete

private void TryConfigureServerPort(Func<IServerAddressesFeature?> serverAddressFeatureAccessor)
{
if (_kestrelPort.HasValue)
{
var saf = serverAddressFeatureAccessor();
if (saf is not null)
{
saf.Addresses.Clear();
saf.Addresses.Add($"http://127.0.0.1:{_kestrelPort}");
saf.PreferHostingUrls = true;
}
}
}

private void ConfigureBuilderToUseKestrel(IWebHostBuilder builder)
{
if (_configureKestrelOptions is not null)
{
builder.UseKestrel(_configureKestrelOptions);
}
else if (_kestrelPort is int port)
{
// Configure the endpoint here (during the app's own startup) instead of mutating
// IServerAddressesFeature after the host is built. Apps that start themselves
// (e.g. minimal apps run via DeferredHostBuilder) bind Kestrel on their own thread
// and can make the addresses collection read-only before the factory could update it,
// causing an intermittent InvalidOperationException.
builder.UseKestrel(options => options.Listen(IPAddress.Loopback, port));
}
else
{
builder.UseKestrel();
Expand Down Expand Up @@ -655,7 +649,6 @@ protected virtual TestServer CreateServer(IServiceProvider serviceProvider)
protected virtual IHost CreateHost(IHostBuilder builder)
{
var host = builder.Build();
TryConfigureServerPort(() => GetServerAddressFeature(host));
host.Start();
return host;
}
Expand Down
Loading