Masz dwie różne problemy tutaj:
wątku Blokowanie
host.Run()
rzeczywiście blokuje główny wątek. Tak więc użyj host.Start()
(lub await StartAsync
na 2.x) zamiast host.Run()
.
Jak uruchomić przeglądarkę internetową
Jeśli używasz ASP.NET Rdzeń nad .NET Framework 4.x, Microsoft says można po prostu użyć:
Process.Start("http://localhost:5000");
Ale jeśli jesteś targetowanie wieloplatformowego .NET Core, powyższa linia zawiedzie. Nie ma jednego rozwiązania używającego .NET Standard
, które działa na każdej platformie. Windows-jedynym rozwiązaniem jest:
System.Diagnostics.Process.Start("cmd", "/C start http://google.com");
Edit: I stworzył ticket oraz MS dev odpowiedział, że jako-of-dziś, jeśli chcesz multi wersję platformy należy zrobić to ręcznie, jak:
public static void OpenBrowser(string url)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Process.Start(new ProcessStartInfo("cmd", $"/c start {url}")); // Works ok on windows
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
Process.Start("xdg-open", url); // Works ok on linux
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
Process.Start("open", url); // Not tested
}
else
{
...
}
}
Wszystko razem teraz:
using System.Threading;
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Start();
OpenBrowser("http://localhost:5000/");
}
public static void OpenBrowser(string url)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Process.Start(new ProcessStartInfo("cmd", $"/c start {url}"));
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
Process.Start("xdg-open", url);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
Process.Start("open", url);
}
else
{
// throw
}
}
}