Codementor Events

Live Reloading Angular Application with ASP.NET Core in Visual Studio 2017

Published Feb 02, 2018
Live Reloading Angular Application with ASP.NET Core in Visual Studio 2017

Running “ ng serve” in visual studio debug mode

While working on angular application with asp.net core in VS 2017, I came across this excellent article by Levi Fuller 👇

How to build an Angular Application with ASP.NET Core in Visual Studio 2017, visualized
_With an arguably gratuitous number of visuals and code, we’ll learn how to build a ready-to-deploy web application…_medium.com

The application runs fine when I start using the “ng serve” command in the command prompt and the live-reloading works with the proxy modifications.


I wanted to run the application in “Debug” mode in visual studio. So here are the changes that I have done which enables the “ng serve” to start when the application is started in the “Debug” mode:

  1. Modify the “start” script in package.json to this:

“start”: “ng serve — proxy-config proxy.config.json”,
  1. Modify the “Startup.cs” file and add the following changes:
  • Add a Process variable in the Startup class:

private Process _npmProcess;
  • Modify the “Configure” method and add the following code for starting the npm process:

if (env.IsDevelopment())
{
  try
    {
    	// Start the ng serve process using npm start
        _npmProcess = new Process
        {
            StartInfo = new ProcessStartInfo
            {
        	    FileName = "cmd.exe",
                Arguments = "/C npm start",
                UseShellExecute = false
            }
        };
    
       	// Start process
    	_npmProcess.Start();

    // Register the application shutdown event
    	var applicationLifetime = app.ApplicationServices.GetRequiredService<IApplicationLifetime>();
         
     	applicationLifetime.ApplicationStopping.Register(OnShutDown);
  }
    catch (Exception ex)
    {
    	Console.WriteLine(ex);
    }
}
  • Add the “OnShutDown” method in the Startup class:

private void OnShutDown()
{
    if (_npmProcess != null)
    {
        try
        {
            Console.WriteLine($"Killing process npm process ( {_npmProcess.StartInfo.FileName} {_npmProcess.StartInfo.Arguments} )");
            _npmProcess.Kill();
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Unable to Kill npm process ( {_npmProcess.StartInfo.FileName} {_npmProcess.StartInfo.Arguments} )");
            Console.WriteLine($"Exception: {ex}");
        }
    }
}
  1. Now run the application from Visual Studio and “ng serve” will be started inside the asp.net core application’s console:

  1. Update/Add something in the angular app source and you should be able to see the rebuild of the bundles and live-reloading in the browser.

Hope this article helps someone 😃

Cheers 🙌

Discover and read more posts from Faisal
get started
post commentsBe the first to share your opinion
Show more replies