How do I launch the web browser after starting my asp net core application

Launching the Web Browser in ASP.NET Core

Launching the web browser after starting an ASP.NET Core application can be achieved using the .Start method from the System. . This method allows you to start a process, in this case, the web browser, with a specified URL.

To launch the web browser, you need to determine the URL of your ASP.NET Core application. This can be done by retrieving the base URL of the application using the IWebHostEnvironment service.

Here's an example of how you can launch the web browser after starting your ASP.NET Core application:


using System.Diagnostics;
using .AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;

public class Program
{
    public  void Main(string[] args)
    {
        var host = CreateHostBuilder(args).Build();
        
        // Get the base URL of the application
        var baseUrl = host..GetService().WebRootPath;
        
        // Launch the web browser with the application URL
        Process.Start(new ProcessStartInfo { FileName = baseUrl });
        
        host.Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup();
            });
}

In the above example, we first create an of the IWebHostEnvironment service by retrieving it from the host's services. Then, we use the WebRootPath property to get the base URL of the application.

Next, we use the Process.Start method to launch the web browser. We pass the base URL as the FileName parameter to open the browser with the application URL.

Finally, we call the host.Run() method to start the ASP.NET Core application.

By following the above , the web browser will launch after starting your ASP.NET Core application.

Rate this post

Leave a Reply

Your email address will not be published. Required fields are marked *

Table of Contents