Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
30 changes: 6 additions & 24 deletions src/mono/wasm/host/WebServer.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,9 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
Expand All @@ -21,6 +17,7 @@ public class WebServer
internal static async Task<(ServerURLs, IWebHost)> StartAsync(WebServerOptions options, ILogger logger, CancellationToken token)
{
string[]? urls = new string[] { $"http://127.0.0.1:{options.Port}", "https://127.0.0.1:0" };
TaskCompletionSource<ServerURLs> realUrlsAvailableTcs = new();

IWebHostBuilder builder = new WebHostBuilder()
.UseKestrel()
Expand All @@ -43,6 +40,7 @@ public class WebServer
}
services.AddSingleton(logger);
services.AddSingleton(Options.Create(options));
services.AddSingleton(realUrlsAvailableTcs);
services.AddRouting();
})
.UseUrls(urls);
Expand All @@ -53,27 +51,11 @@ public class WebServer
IWebHost? host = builder.Build();
await host.StartAsync(token);

ICollection<string>? addresses = host.ServerFeatures
.Get<IServerAddressesFeature>()?
.Addresses;
if (token.CanBeCanceled)
token.Register(async () => await host.StopAsync());

string? ipAddress =
addresses?
.Where(a => a.StartsWith("http:", StringComparison.InvariantCultureIgnoreCase))
.Select(a => new Uri(a))
.Select(uri => uri.ToString())
.FirstOrDefault();

string? ipAddressSecure =
addresses?
.Where(a => a.StartsWith("https:", StringComparison.OrdinalIgnoreCase))
.Select(a => new Uri(a))
.Select(uri => uri.ToString())
.FirstOrDefault();

return ipAddress == null || ipAddressSecure == null
? throw new InvalidOperationException("Failed to determine web server's IP address or port")
: (new ServerURLs(ipAddress, ipAddressSecure), host);
ServerURLs serverUrls = await realUrlsAvailableTcs.Task;
return (serverUrls, host);
}

}
Expand Down
52 changes: 51 additions & 1 deletion src/mono/wasm/host/WebServerStartup.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,19 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Net.WebSockets;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

#nullable enable
Expand All @@ -16,11 +23,17 @@ namespace Microsoft.WebAssembly.AppHost;
internal sealed class WebServerStartup
{
private readonly IWebHostEnvironment _hostingEnvironment;
private ILogger? _logger;

public WebServerStartup(IWebHostEnvironment hostingEnvironment) => _hostingEnvironment = hostingEnvironment;

public void Configure(IApplicationBuilder app, IOptions<WebServerOptions> optionsContainer)
public void Configure(IApplicationBuilder app,
IOptions<WebServerOptions> optionsContainer,
TaskCompletionSource<ServerURLs> realUrlsAvailableTcs,
ILogger logger,
IHostApplicationLifetime applicationLifetime)
{
_logger = logger;
var provider = new FileExtensionContentTypeProvider();
provider.Mappings[".wasm"] = "application/wasm";
provider.Mappings[".cjs"] = "text/javascript";
Expand Down Expand Up @@ -73,6 +86,43 @@ public void Configure(IApplicationBuilder app, IOptions<WebServerOptions> option
});
}

applicationLifetime.ApplicationStarted.Register(() =>
{
TaskCompletionSource<ServerURLs> tcs = realUrlsAvailableTcs;
try
{
ICollection<string>? addresses = app.ServerFeatures
.Get<IServerAddressesFeature>()
?.Addresses;

string? ipAddress = null;
string? ipAddressSecure = null;
if (addresses is not null)
{
ipAddress = GetHttpServerAddress(addresses, secure: false);
ipAddressSecure = GetHttpServerAddress(addresses, secure: true);
}

if (ipAddress == null)
tcs.SetException(new InvalidOperationException("Failed to determine web server's IP address or port"));
else
tcs.SetResult(new ServerURLs(ipAddress, ipAddressSecure));
}
catch (Exception ex)
{
_logger?.LogError($"Failed to get urls for the webserver: {ex}");
tcs.TrySetException(ex);
throw;
}

static string? GetHttpServerAddress(ICollection<string> addresses, bool secure)
=> addresses?
.Where(a => a.StartsWith(secure ? "https:" : "http:", StringComparison.InvariantCultureIgnoreCase))
.Select(a => new Uri(a))
.Select(uri => uri.ToString())
.FirstOrDefault();
});

// app.UseEndpoints(endpoints =>
// {
// endpoints.MapFallbackToFile(options.DefaultFileName);
Expand Down