Click here to Skip to main content
15,885,914 members
Articles / Web Development / ASP.NET / ASP.NET Core

Integrating ASP.Net Core 2.0 and Angular 4 projects using CLI and Visual Studio Code - Beginners Tutorial

Rate me:
Please Sign up or sign in to vote.
4.94/5 (16 votes)
16 Sep 2017CPOL7 min read 64.5K   17   12
Step-by-step tutorial on integrating projects created using angular-cli and dotnet-cli

Contents

Introduction

Nowadays, gone are the frameworks with monolithic approach. Latest frameworks tend to be more modular. ASP.Net Core is a re-write of ASP.Net but a lot more modular same with Angular 4 (2) from AngularJS.

These modern frameworks offers CLI (Command Line Interface) Tools that give developers more option in developing next generation applications. CLI tools give developers the freedom to work from any operating system. It is evident that GUI tools do not work on all major operating systems. Best example of this is Visual Studio which works only on Windows and just recently on Mac.

One of the ways to create an SPA (Single Page Application) project made of Angular and ASP.NET Core Web API is to use Visual Studio Template. Although this approach is convenient, you are dependent with the template which is created and being updated by some individuals who may not be even part of the framework developers.

This tutorial is a starter guide for developers who heard and became curious about the increasing popularity of Angular and ASP.NET Core but do not know how to start.

What you will learn

  1. How to create an Angular project using Angular CLI
  2. How to create an ASP.Net Core Wep API using Dotnet Core CLI
  3. How to integrate both of these projects
  4. How to install, update and use latest CLIs

Environment

This tutorial is for Microsoft Windows but it can be used as guide for other operating systems except for the installation part.

  • Microsoft Windows 10 Version 1703, 64 bit (created on this version)

Key steps

Here are the key steps to take:

  1. Download and install SDKs
  2. Download and install Visual Studio Code
  3. Update npm
  4. Install Angular CLI
  5. Check versions
  6. Create Angular project (this is where real work begins)
  7. Create ASP.Net Core Web API project
  8. Integrate projects

Step 1: Download and install SDKs

Please note that installation processes are different on every operating system. Step-by-step installation of SDK is not covered in this tutorial. The screenshots are the first window after executing the installer for Windows.

Download and install SDKs:

  1. .NET Core 2.0 SDK
  2. Node.js SDK

 

  • .Net Core 2.0

Download .NET Core 2.0 SDK installer.

https://www.microsoft.com/net/download/core

Install the downloaded installer.

.NET Core SDK Installer

  • Node.js

Download Node.js SDK installer.

Download Current for latest features.

Node.js SDK Installer

Install the downloaded installer.

Install Node.js

Step 2: Download and install Visual Studio Code

Use Microsoft Visual Studio Code (VS Code) as GUI tool, IDE (Integrated Development Environment) for development.

Download Microsoft Visual Studio Code installer.

Image 5

Install. Install the downloaded installer.

Image 6

 

Step 3. Update npm

Node.js installer installs npm by default but it maybe not the latest.

Update npm from command line as Administrator. Follow the guide here on how to run command line (cmd.exe) as Administrator.

Update Node Package Manager Image

Do not close the command line for it will be used on succeeding steps.

Explanation:

cd\
    - change Directory from current path to the root path. In the screenshots above, C: is the root path.

npm update -g npm
   - update the globally (-g) installed Node Package Manager (NPM)

Step 4. Install Angular CLI

Install angular cli from command line.

 Install Angular CLI image

Explanation:

npm install -g @angular/cli

   - using npm, angular cli is installed globally.

Step 5. Check versions (this is optional)

At this point, check versions of SDK/CLI installed.

Image 9

Explanation:

dotnet --version
   - displays .NET Core SDK version

node -v
  - displays Node.js version

npm -v
  - displays NPM version

ng -v
  - displays Angular CLI version

Step 6. Create Angular project (this is where real work begins)

Create an Angular project using Angular (ng) CLI.

Image 10

Explanation:

cd projects
   - change current path to "projects" folder under the current path. This is to organize projects into one folder
ng new hello-world
   - using Angular (ng) CLI, create a folder "hello-world" under the current path and add new angular project with same name
   - issuing "ng new hello-word & cd new hello-world" from command line will immediately change the current path to "hello-world" after creating the project

Run the newly created Angular project.

Image 11

Explanation:

cd hello-world
   - change current path to "hello-world" folder under the current path

ng server --open
   - "ng serve" builds the application and starts a web server
   - "--open" opens web browser after successful build and web server is started. For other options, refer here. Without using "--open" option, you can see the output by opening web browser on "http://localhost:4200" as url.

Created web page will be displayed in the web browser.

Image 12

Terminate the web server by issuing "ctrt + c", then press "Y" then "Enter".

Image 13

Step 7. Create ASP.Net Core Web API project

Although the succeeding processes can still be executed using command line, VS Code will be used this time. In fact, all Angular commands previously done in command line can also be executed inside VS Code. I prefer working inside VS Code to prevent switching between opened windows.

Open the project in VS Code using command line (1st Way)

Image 14

Explanation:

code .

   - open the current folder in VS Code

Open project in VS Code (2nd Way)

After running VS Code, select the project folder by clicking "File-Open Folder..." from menu.

Image 15

Image 16

Show integrated terminal (command line) in VS Code by clicking "View-Integrated Terminal" from menu or "Ctrl + ~" as keyboard shortcut. This explains why everything can be executed inside VS Code.

Image 17

Image 18

From the terminal (integrated command line), create new ASP.NET Core Web API project.

Image 19

Explanation:

dotnet new webapi

   - using DotNet CLI, create a new Web API project. Without specifying options, Dotnet CLI will create a project with name equals to the folder where "new" command is issued. For additional information, refer to this link.

Select "Yes" and "Restore" on the messages displayed by VS Code. Settings will be added to enable debugging after clicking "Yes". Just note that debugging is included topic in this tutorial so it doesn't matter whatever option you opt to select. Clicking "Restore" will restore dependies or libraries needed for ASP.NET Core Web API.

Image 20

Notice in Side Bar "hello-world.csproj" has been added. That's the newly added ASP.NET Core Web API project. If Side Bar is not displayed, click "View-Toggle Side Bar" from menu to show/hide it or "Ctrl + B" if you prefer keyboard shortcut.

Image 21

At this point, two projects exists: the existing Angular project and the newly added ASP.NET Core Web API project. Although the projects are on the same folder, it has no relation right now.

Build and run the newly created ASP.NET Core Web API project.

Image 22

Open web browser on "http://localhost:5000/api/values" as url. Be sure to add "/api/values" to the url because that's the default route for the newly created Web API.

Image 23

Terminate the web server by pressing "Ctrl + C" at the integrated terminal.

Image 24

Step 8. Integrate projects

Open ".angular-cli.json" and change "outDir" under "apps" to "wwwroot". This tells Angular CLI to save the compilation output files to the same folder where DotNet CLI is outputting.

Image 25

Delete "ValuesController.cs" from "Controllers" folder and replacing it with a simple Web API that just returns a simple "hello" greetings.

Image 26

Create "HelloController.cs" inside "Controllers" folder. Right click on "Controllers" folder and click "New File". Name the file to "HelloContoller.cs".

Image 27

Image 28

Paste the code below.

[Controllers\HelloController.cs]

ASP.NET
using System;
using Microsoft.AspNetCore.Mvc;

namespace hello_world
{
    [Route("api/[Controller]")]
    public class HelloController : Controller
    {
        [HttpGet]
        public IActionResult Greetings() {
            return Ok("Hello from ASP.NET Core Web API.");
        }
    }
}

Modify Startup.cs to include "UseDefaultFiles" and "UseStaticFiles" in the HTTP request pipeline.

Image 29

With "UseDefaultFiles", requests to a folder will search for:

  • default.htm
  • default.html
  • index.htm
  • index.html

"UseStaticFiles" makes the files in web root (wwwroot by default) servable.

For additional information regarding UseDefaultFiles" and "UseStaticFiles", refer to this link.

At this timing, our work on Web API project is completed. Let's go back to Angular and consume Web API from Angular.

Create a new file "app.service.ts" inside "src\app" folder and paste the code below.

[src\app\app.service.ts]

import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Rx';

// Import RxJs required methods
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

@Injectable()
export class AppService {
    private greetUrl = 'api/Hello';

    // Resolve HTTP using the constructor
    constructor(private _http: Http) { }

    sayHello(): Observable<any> {
        return this._http.get(this.greetUrl).map((response: Response) => {
            return response.text();
        });
    }
}

Modify "app.module.ts" and add "AppService" as providers. Then import "HttpModule"

[src\app\app.module.ts]

ASP.NET
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { AppService } from './app.service';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpModule
  ],
  providers: [AppService],
  bootstrap: [AppComponent]
})
export class AppModule { }

Image 30

Modify "app.component.ts" to inject "AppService".

[src\app\app.component.ts]

import { Component, OnInit } from '@angular/core';
import { Http, Response } from '@angular/http';

import { AppService } from './app.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  greetings = '';

  constructor(private _appService: AppService) { }

  ngOnInit(): void {
    this._appService.sayHello()
      .subscribe(
      result => {
        this.greetings = result;
      }
      );
  }
}

Change the contents of "app.component.html".

[src\app\app.component.html]

HTML
<h2 class='panel-heading'>
  {{greetings}}
</h2>
<hr/>

Build Angular.

Image 31

Build DotNet.

Image 32

Run DotNet.

Image 33

Open web browser to "http://localhost:5000/". Notice that "api/*" is not included in the url. When page is loaded, Angular is loaded first then web api is consumed inside Angular thus showing the greetings.

Image 34

That's it.

What's next?

We already learned how to create Angular and DotNet projects using each respective CLI. We were also able to integrate the two projects. This means we are now capable of using the best out of CLI of two completely different framework. So, what's next?

1. Learn ASP.Net Core Web API from here.

2. Learn Angular from here.

History

09/16/2017 - Initial creation

09/17/2017 - Fixed broken images

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Systems Engineer
Philippines Philippines
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralThanks Such a nice article Pin
yadlaprasad14-Feb-18 18:35
yadlaprasad14-Feb-18 18:35 
QuestionThis is not really "integrating"... Pin
Luperco10-Jan-18 4:49
Luperco10-Jan-18 4:49 
AnswerRe: This is not really "integrating"... Pin
@sof-mckoy10-Jan-18 22:56
professional@sof-mckoy10-Jan-18 22:56 
GeneralRe: This is not really "integrating"... Pin
Luperco12-Jan-18 6:55
Luperco12-Jan-18 6:55 
QuestionThanks Pin
Odairto Martin6-Jan-18 8:14
Odairto Martin6-Jan-18 8:14 
QuestionMuch easier way Pin
RogerDW2-Jan-18 22:27
RogerDW2-Jan-18 22:27 
AnswerRe: Much easier way Pin
@sof-mckoy5-Jan-18 2:44
professional@sof-mckoy5-Jan-18 2:44 
QuestionIs it possible to use webpack and dotnet -watch for instant code change? Pin
Member 36205451-Dec-17 5:55
Member 36205451-Dec-17 5:55 
QuestionRefresh Pin
Member 1352183214-Nov-17 19:10
Member 1352183214-Nov-17 19:10 
QuestionUpgrade Pin
BongGuiao7-Oct-17 12:52
BongGuiao7-Oct-17 12:52 
QuestionHas Anyone Been Able To Deploy This Application To IIS? Pin
James Whit...3-Oct-17 5:31
James Whit...3-Oct-17 5:31 
AnswerRe: Has Anyone Been Able To Deploy This Application To IIS? Pin
Sridhar Sathya9-Oct-17 5:39
Sridhar Sathya9-Oct-17 5:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.