How do I launch the web browser after starting my ASP.NET Core application?
Yet another option here is to resolve an IApplicationLifetime
object in Startup.Configure
and register a callback on ApplicationStarted
. That event is triggered when a host has spun up and is listening.
public void Configure(IApplicationBuilder app, IApplicationLifetime appLifetime)
{
appLifetime.ApplicationStarted.Register(() => OpenBrowser(
app.ServerFeatures.Get<IServerAddressesFeature>().Addresses.First()));
}
private static void OpenBrowser(string url)
{
Process.Start(
new ProcessStartInfo("cmd", $"/c start {url}")
{
CreateNoWindow = true
});
}
You have two different problems here:
Thread Blocking
host.Run()
indeed blocks the main thread. So, use host.Start()
(or await StartAsync
on 2.x) instead of host.Run()
.
How to start the web browser
If you are using ASP.NET Core over .NET Framework 4.x, Microsoft says you can just use:
Process.Start("http://localhost:5000");
But if you are targeting multiplatform .NET Core, the above line will fail. There is no single solution using .NET Standard
that works on every platform. The Windows-only solution is:
System.Diagnostics.Process.Start("cmd", "/C start http://google.com");
Edit: I created a ticket and a MS dev answered that as-of-today, if you want a multi platform version you should do it manually, like:
public static void OpenBrowser(string url)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Process.Start(new ProcessStartInfo(url) { UseShellExecute = true }); // 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
{
...
}
}
All together now:
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(url) { UseShellExecute = true });
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
Process.Start("xdg-open", url);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
Process.Start("open", url);
}
else
{
// throw
}
}
}