c# - How do I launch the web browser after starting my ASP.NET Core application? -
i have asp.net core application used client multiple users. in other words, not hosted on central server , run published executable anytime need use application.
in program.cs
file there's following:
var host = new webhostbuilder() .usekestrel() .usecontentroot(directory.getcurrentdirectory()) .useiisintegration() .usestartup<startup>() .build(); host.run();
i default web browser automatically open avoid redundant step of user having open browser , manually put in http://localhost:5000
address.
what best way achieve this? calling program.start
after call run()
won't work because run
blocks thread.
you have 2 different problems here:
thread blocking
host.run()
indeed blocks main thread. so, use host.start()
(or await startasync
on 2.x) instead of host.run()
.
how start web browser
if using asp.net core on .net framework 4.x, microsoft says can use:
process.start("http://localhost:5000");
but if targeting multiplatform .net core, above line fail. there no single solution using .net standard
works on every platform. windows-only solution is:
system.diagnostics.process.start("cmd", "/c start http://google.com");
edit: created ticket , ms dev answered as-of-today, if want multi platform version should manually, like:
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 { ... } }
all 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("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 } } }
Comments
Post a Comment