How to integrate Angular 9 with an ASP.NET Core Project

Yi-Fang Pan
4 min readMar 7, 2020

--

Upgrade Visual Studio template to Angular 9

Preparation

  • Install Visual Studio 2019
  • Install Visual Studio Code ( Optional )
  • Install Node.js
  • Install Angular CLI

npm install -g @angular/cli

Environment

  • ASP.NET Core 3.1
Use dotnet --version to check .NET Core Version
  • Angular 9
Use ng version to check Angular Version

Create ASP.NET Core Web Application with Angular 8

  1. Create ASP.NET Core Web Application Project

2. Select Angular and check version is ASP.NET Core 3.1

Check Angular version in package.json

  • Visual Studio 2019 Template is using Angular 8
package.json

Integrate Angular 9 in project

This tutorial uses the Visual Studio Code. You can use a different way to complete it.

  • Delete ClientApp Folder
  • Create an Angular project and setup project name with ClientApp. ( Make sure in the .csproj folder )
ng new ClientApp --routing --style=css --skip-git --skip-install
  • Check Angular version is Angular 9
package.json

Run Project

  1. Using Visual Studio 2019 and right-click project to build the project. This may take several minutes to Restore dependencies for the first time.
  2. Check Build result
  3. Click IIS Express to run website

Now Angular 9 in your ASP.NET Core Project is work.

How ASP.NET Core build can restore Angular node_module?

ASP.NET Core .csproj will check is exist install node and run npm install before build .NET Core project.

Angular9NETCoreTemplate.csproj

Issue

- An unhandled exception occurred while processing the request.

If you can’t run the project successfully and get the error page like below, you should modify package.json.

  • Solution:Refer to this post, using ng serve --verbose to solve this issue.

How run ASP.NET Core and Angular at the same time?

Startup.cs use UseAngularCliServer to call npm start, and npm start will trigger package.json ng serve

Startup.cs

Publish Project

  • Install ASP.NET Core Runtime 3.1.1 in your server

https://dotnet.microsoft.com/download/dotnet-core/3.1

  • Run dotnet publish -c release to publish the project

If your website is not in the root website and you get 404

1. Set base-href in the build setting.

Example:ng build --base-href=/Angular9DotNetCore3Template/

2. .NET Core set running Angular SPA RootPath is ClientApp/dist, so we will change angular.json “outputPath”: “dist/ClientApp” to “outputPath”: “dist”

Startup.cs

Republish the project dotnet publish -c release and check the publish file.

How to publish ASP.NET Core and Angular at the same time?

When using command line dotnet publish -c release to publish the project, ASP.NET Core Project will call npm run build and build file in ClientApp\dist

Publish file in ..\Angular9NETCoreTemplate\bin\release\netcoreapp3.1\publish\

--

--