更新时间:2022-11-06 12:52:53
您在这里有两个不同的问题:
You have two different problems here:
线程阻塞
host.Run()
确实阻塞主线程。因此,使用 host.Start()
(或在2.x上 await StartAsync
)而不是 host.Run()
。
host.Run()
indeed blocks the main thread. So, use host.Start()
(or await StartAsync
on 2.x) instead of host.Run()
.
如何启动网络浏览器
如果通过.NET Framework 4.x使用ASP.NET Core,则Microsoft 说,您可以使用:
If you are using ASP.NET Core over .NET Framework 4.x, Microsoft says you can just use:
Process.Start("http://localhost:5000");
但是,如果您定位的是多平台.NET Core,则上述行将失败。使用 .NET Standard
的解决方案无法在每个平台上使用。仅限Windows的解决方案是:
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");
编辑:我创建了门票和一位MS开发人员今天回答说,如果您想要一个多平台版本,则应该手动执行,例如:
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
{
...
}
}
现在在一起:
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
}
}
}