Add The latest Angular CLI project(7.x) to ASP.Net Core 2.1 project

Frank Chen
6 min readFeb 9, 2019

--

I published Add Angular 5 CLI project to ASP.Net Core 2.0 project last year and found out a lot of people like that. As Angular continues to release a new version (7.xx) and the latest released Visual Studio 2017 update cannot keep their Angular project up-to-date, I thought it would make sense to create another article to reflect the latest updates. The idea is to find a general process to allow people update their ASP.NET Core projects whenever there is a new Angular Cli released.

  • Create a ASP.Net project by clicking Add new project->Web->ASP.NET Core Web Application. Select the following options at “New ASP.NET Core Web Application” dialog:

○ .NET Core
○ ASP.NET Core 2.1
○ Web Application (Model-View-Controller)
○ Click “Ok”
○ For example, we name the web project as ASPCoreAngular7.

  • Run command.exe as administrator and go to ASPCoreAngular7 project folder.
  • Make sure you have Angular Cli installed. If you don’t, run the following command:
npm install -g @angular/cli@latest
  • Enter the following command to create an Angular Cli with same folder as ASP.NET Core project. The purpose for that is to have package.json and .angular-cli.json are located at the same level as the ASP.NET Core project folder. I also used — directory ASPCoreAngular7 which makes the Angular App source folder is same as the project folder.

○ — routing: create routing module.
○ — skip-git: skip git creation
○ — directory: specify the folder as ASPCoreAngular7 which will generate files under ASP.NET Core Web Application project folder. For this case, when I first created project from VS2017, ASPCoreAngular7 was used for project folder.

Cd C:\EZCodeVSTS\SampleCodes\Angular\V7.0\ASPCoreAngular7SolutionC:\EZCodeVSTS\SampleCodes\Angular\V7.0\ASPCoreAngular7Solution ng new ASPCoreAngular7 — routing true — skip-git true — directory ASPCoreAngular7
  • After we run the command, you should find a “src” folder created under your project folder(ASPCoreAngular7 for this case). All the Cli generated codes are located to here. But the Angular project related files are located under project folder. Such as angular.json, tsconfig.json, tslint.json and so on.
  • At this moment, you can run ng server to test your generated code. You should be able to see a simple Angular Cli page shown in your browser. If you don’t see that, make sure you have all NPM packages installed.
  • VS 2017 also introduced SPA middleware to integrate with Angular server when you want to F5 debug from VS. in order to have that, you need to have Microsoft.AspNetCore.SpaServices.Extensions. The good thing is Microsoft.AspNetCore.App package already included that package. After you make sure you have “Microsoft.AspNetCore.App” package installed, you can add the following highlighted code to Startup.cs. You will rely on Angular Cli server for F5 debug at development mode. One thing I want to point out here the default StartupTimeout is 50 seconds which might not be enough for Angular Cli compile the code. If you see the error message, you need to change StartupTimeout to longer. I configured it to 5 minutes which had no problem.
public void Configure(IApplicationBuilder app, IHostingEnvironment env){if (env.IsDevelopment()){app.UseDeveloperExceptionPage();}else{app.UseExceptionHandler(“/Home/Error”);app.UseHsts();}app.UseSpa(spa =>{spa.Options.SourcePath = “./”;//to avoid “The Angular CLI process did not start listening for requests within the timeout period of 50 seconds.” issuespa.Options.StartupTimeout = new TimeSpan(0, 5, 0);if (env.IsDevelopment()){spa.UseAngularCliServer(npmScript: “start”);}});app.UseHttpsRedirection();app.UseStaticFiles();app.UseCookiePolicy();app.UseMvc(routes =>{routes.MapRoute(name: “default”,template: “{controller=Home}/{action=Index}/{id?}”);routes.MapSpaFallbackRoute(name: “spa-fallback”,defaults: new { controller = “Home”, action = “Index” });});}
  • After Angular 6, the Angular Cli configuration json file had renamed from .angular-cli.json to .angular.json. The file structure also changed too. In order to allow VS to integrate with Angular Cli server, You also need to make the following highlighted changes in angular.json.

○ “sourceRoot”: define the root folder, for our case, “ClientApp” will be the root of TypeScripts.
○ “build”->”options”->”outputPath”: this is builder output folder. When you create published version, you need to generate Angular files to this folder and reference them from your _layout.cshtml.
○ “build”->”options”->”styles”: the style css you want to include. If you use bootstrap, you need to include bootstrap css to here.
○ “build”->”options”->”scripts”: the JavaScript libraries you want to include. If you use Bootstrap, you need to include Bootstrap and jQuery JavaScript files in here so that Angular Cli will bundle them for you. If you want to use Bootstrap and jQuery CDN from _layout.cshtml, you can skip here.

{“$schema”: “./node_modules/@angular/cli/lib/config/schema.json”,“version”: 1,“newProjectRoot”: “projects”,“projects”: {“ASPCoreAngular7”: {“root”: “”,“sourceRoot”: “src”,“projectType”: “application”,“prefix”: “app”,“schematics”: {},“architect”: {“build”: {“builder”: “@angular-devkit/build-angular:browser”,“options”: {“outputPath”: “./wwwroot/dist”,“index”: “src/index.html”,“main”: “src/main.ts”,“polyfills”: “src/polyfills.ts”,“tsConfig”: “src/tsconfig.app.json”,“assets”: [“src/favicon.ico”,“src/assets”],“styles”: [“src/styles.css”,“node_modules/bootstrap/scss/bootstrap.scss”],“scripts”: [“node_modules/jquery/dist/jquery.min.js”,“node_modules/bootstrap/dist/js/bootstrap.bundle.js”],“es5BrowserSupport”: true},“configurations”: {}},“serve”: {},“test”: {},“lint”: {}}},“ASPCoreAngular7-e2e”: {}},“defaultProject”: “ASPCoreAngular7”}
  • Open up your Views/home/index.cshtml and replace to the following code. <app-root> will be the angular entry point.
@{ViewData[“Title”] = “Home Page”;}
<app-root></app-root>
  • Open up _layout.cshtml, replace the code to the following:
<!DOCTYPE html><html><head><meta charset=”utf-8" /><meta name=”viewport” content=”width=device-width, initial-scale=1.0" /><title>@ViewData[“Title”] — ASPCoreAngular5_2</title><base href=”~/” /></head><body>@RenderBody()@RenderSection(“Scripts”, required: false)</body></html>
  • By default, VS2017 will automatically compile typescript files when you press F5. In order to avoid VS compile your TypeScript code, you need to disable VS2017 to compile TypeScript files. You can first unload your project and open up the project file from editor to add the following xml: It basically tell VS not to compile your TypeScript code.
<PropertyGroup><TargetFramework>netcoreapp2.0</TargetFramework><TypeScriptCompileBlocked>true</TypeScriptCompileBlocked><TypeScriptToolsVersion>Latest</TypeScriptToolsVersion></PropertyGroup>
  • Now, you can hit F5 to start debugger. Your Angular page should be rendering at your default browser.
  • Once you complete your development and would like to publish your code, you need to rely on Angular Cli to build your project and reference them from your ASP.NET view files.
  • Go back to command line and type the following to build your angular solutions. The files will be generated under wwwroot/dist folder. All the libraries and css will be bundled to js files.
Ng build

Open up _layout.cshtml, replace the code to the following:

  • Add the following script references which points to .\wwwroot\dist folder. You can detail file references from./wwwroot/dist/index.html.
<!DOCTYPE html><html><head><meta charset=”utf-8" /><meta name=”viewport” content=”width=device-width, initial-scale=1.0" /><title>@ViewData[“Title”] — ASPCoreAngular5_2</title></head><body>@RenderBody()<script type=”text/javascript” src=”~/dist/runtime.js” asp-append-version=”true”></script><script type=”text/javascript” src=”~/dist/es2015-polyfills.js” nomodule asp-append-version=”true”></script><script type=”text/javascript” src=”~/dist/polyfills.js” asp-append-version=”true”></script><script type=”text/javascript” src=”~/dist/styles.js” asp-append-version=”true”></script><script type=”text/javascript” src=”~/dist/scripts.js” asp-append-version=”true”></script><script type=”text/javascript” src=”~/dist/vendor.js” asp-append-version=”true”></script><script type=”text/javascript” src=”~/dist/main.js” asp-append-version=”true”></script>@RenderSection(“Scripts”, required: false)</body></html>
  • Finally, if you want to integrate with your VS2017 build, you can add the following command to your pre-build command which you can find from right click your project->Property->Build Event
C:\Users\frank.EZCODE\AppData\Roaming\npm\ng.cmd build

I hope you can enjoy it. Feel free to comment if you have questions.

--

--

Responses (4)