Get Going with the Angular and ASP.NET CLIs

Angular and ASP.NET CLIs Header

When learning Angular and ASP.NET Core, it's oftentimes helpful to start with an empty project. However, there are some integration steps required to have Angular and ASP.NET Core work together.

This tutorial shows how to create an Angular, ASP.NET Core project using the command line interfaces (CLI) for both Angular and .NET Core. It demonstrates how to host and debug an ASP.NET Core project in Visual Studio Code.

Prerequisites

The following must be installed to complete this tutorial:

Note: The commands in this article work on a Windows machine with PowerShell. Other platforms may require modifications.

Configure Angular

  1. Install Angular CLI globally to make the commands available in any directory

    npm install -g @angular/cli
    
  2. Use the newly installed Angular CLI to scaffold a new project. This command creates a new directory to house your application. It may take a couple minutes to complete because the utility installs the npm packages for Angular, the build, and testing.

    ng new my-directory
    
  3. Navigate into the repository and verify the application by running it with the Angular CLI. Use the --open argument to open the application in the default browser.

    cd my-directory
    ng serve --open
    

    The Angular CLI runs the application on a Node.js web server and you will see the stub page.

    Angular CLI Stub Page

  4. Terminate the running web server with the key combination Ctrl + C to continue in the command window.

Configure ASP.NET Core

  1. In the repository, use the .NET Core CLI to scaffold an empty ASP.NET Core project.

    dotnet new web
    

    Note: The dotnet new command scaffolds the .NET project within the current working directory whereas the Angular CLI command ng new creates a new directory to contain the generated Angular code.

  2. Install the ASP.NET static file support middleware.

    dotnet add package Microsoft.AspNetCore.StaticFiles
    
  3. Open the repository in Visual Studio Code

    code .
    
  4. Visual Studio Code prompts you to configure the application and to restore .NET packages. Press Yes and Restore respectively. The editor generates a .vscode folder containing configuration files and downloads the .NET Core dependencies.

    .NET Core Configuration Prompt

    Tip: If the prompt doesn't appear initially, open a C# file in the editor.

  5. Configure the Angular CLI to output the Angular build to the wwwroot folder. Open the .angular-cli.json configuration file and change "outDir": "dist" to "outDir": "wwwroot".

    {
    // ...
    "apps": [
     {
        "root": "src",
        "outDir": "wwwroot",
        // ...
    }
    }
    
  6. Configure static file support in the Startup.cs file. The Configure method should have the following code.

    public void Configure(IApplicationBuilder app,
      IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
      loggerFactory.AddConsole();
    
      if (env.IsDevelopment())
      {
          app.UseDeveloperExceptionPage();
      }
    
      app.UseDefaultFiles();
      app.UseStaticFiles();
    }
    
  7. Add a build step to the .csproj file to build the Angular application with the Angular CLI.

    <Target Name="AngularBuild" AfterTargets="Build">
      <Exec Command="npm run build" />
    </Target>
    
  8. Press the F5 key to run the ASP.NET application with Visual Studio Code's debugger. The Angular application is now hosted from ASP.NET Core instead of Node.js. Notice how ASP.NET Core uses port 5000 by default as opposed to 4200 with the Angular CLI.

    Angular CLI Stub Page on ASP.NET Core

    Completed Startup.cs Code:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Http;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Logging;
    
    namespace my_directory
    {
      public class Startup
      {
          // This method gets called by the runtime. Use this method to add  services to the container.
          // For more information on how to configure your application, visit  https://go.microsoft.com/fwlink/?LinkID=398940
          public void ConfigureServices(IServiceCollection services)
          {
          }
    
          // This method gets called by the runtime. Use this method to  configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app,
            IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole();
    
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
    
            app.UseDefaultFiles();
            app.UseStaticFiles();
        }
      }
    }
    

    Completed my-directory.csproj Code:

    <Project Sdk="Microsoft.NET.Sdk.Web">
    <PropertyGroup>
      <TargetFramework>netcoreapp1.1</TargetFramework>
    </PropertyGroup>
    
    <ItemGroup>
      <Folder Include="wwwroot\" />
    </ItemGroup>
    
    <ItemGroup>
      <PackageReference Include="Microsoft.AspNetCore" Version="1.1.1" />
      <PackageReference Include="Microsoft.AspNetCore.StaticFiles"  Version="1.1.1" />
    </ItemGroup>
    
    <Target Name="AngularBuild" AfterTargets="Build">
      <Exec Command="npm run build" />
    </Target>
    </Project>
    

Conclusion

The tooling has finally come together for both Angular and ASP.NET so that anyone can easily create an application using the command line.

Use the steps here to build the foundation and then move to integrate other features like routing and authentication. In fact, learn to integrate routing right here.

Have you been using the CLI for Angular or ASP.NET Core? What do you like or dislike about them? Please leave a note in the comments.

7 thoughts on “Get Going with the Angular and ASP.NET CLIs”

  1. When I tried to step 8, I got an error message that the build script was missing. I had to add that script to the package.json file for it to work. I added “build”: “ng serve” because I didn’t know what else to do.

    Did you leave out a step? Or did I do something wrong?

    1. Interesting. You are absolutely correct. I just double-checked the latest version “1.0.0” and it already has the “build”: “ng serve” in the generated package.json file. Double check to see if maybe you have an old version of the CLI installed.

      1. Try ‘npm install -g @angular/cli@latest’ to make sure the global package is updated.

      2. Check to see if you might have the ‘angular-cli’ package installed globally (npm ls -g –depth 0). This was the old version of the cli which is deprecated in favor of @angular/cli.

      Hope that helps.

    1. The web template may not be available in that version of the SDK. Try downloading the latest version from: https://www.microsoft.com/net/download/core

      For instance, my version is 1.0.0 (notice the preview suffix is gone)

      If you did install it, there are a couple other items I can think of:

      1. Your PATH variable may not be pointing to right version
      2. If you have a global.json file in your project directory, that could be overwriting the version used for the application

      Hope that helps

  2. Thanks Aaron. It works like a charm. I could not figure out how I can debug typescript though. Do you have an idea?

    1. Great! Your best bet is to debug with the browser developer tools. Under the covers, the Angular CLI uses webpack to generate source maps for the .ts files. Even though the browser doesn’t run the TypeScript code, the .ts files are displayed in the debugger (location varies by browser). Set a breakpoint, and you can step through your TypeScript. The VSCode debugger attaches to the .NET Core process for server-side (C#) debugging.

Leave a Reply

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