Click here to Skip to main content
13,633,761 members
Click here to Skip to main content
Add your own
alternative version


16 bookmarked
Posted 5 Sep 2017
Licenced CPOL

Getting Started with ASP.NET Core and Angular4 using WEB API

, 12 Sep 2017
Rate this:
Please Sign up or sign in to vote.
In this article, let’s see on how to getting started with ASP.NET Core and using Web API.


In this article, let’s see on how to getting started with ASP.NET Core and using Web API.


Make sure, you have installed all the prerequisites in your computer. If not, then download and install all, one by one.

  1. First, download and install Visual Studio 2017 from this link.
  2. Download and install .NET Core 1.0.1 
  3. Download and install Node.js v4.0 or above. I have installed V6.11.2 (Download link).

First Download and Install the Visual Studio 2017

Select depend on your need and install the Visual Studio 2017 on your computer. If you have already installed Visual Studio 2017 then skip this part.

Once Install you can open the Visual Studio 2017 to create your first ASP.NET Core and Angular4 application.

Using the code

Create a Database and Table

We will be using our SQL Server database for our WEB API and EF. First, we create a database named StudentsDB and a table as StudentMaster. Here is the SQL script to create Database table and sample record insert query in our table. Run the below query in your local SQL server to create Database and Table to be used in our project.

-- 1) Check for the Database Exists .If the database is exist then drop and create new DB  
IF EXISTS (SELECT [name] FROM sys.databases WHERE [name] = 'StudentsDB' )  
USE StudentsDB  
-- 1) //////////// StudentMasters  
IF EXISTS ( SELECT [name] FROM sys.tables WHERE [name] = 'StudentMasters' )  
DROP TABLE StudentMasters  
CREATE TABLE [dbo].[StudentMasters](  
        [StdName] [varchar](100) NOT NULL,     
        [Email]  [varchar](100) NOT NULL,     
        [Phone]  [varchar](20) NOT NULL,     
        [Address]  [varchar](200) NOT NULL  
-- insert sample data to Student Master table  
INSERT INTO [StudentMasters]   ([StdName],[Email],[Phone],[Address])  
     VALUES ('Shanu','','01030550007','Madurai,India')  
INSERT INTO [StudentMasters]   ([StdName],[Email],[Phone],[Address])  
     VALUES ('Afraz','','01030550006','Madurai,India')  
INSERT INTO [StudentMasters]   ([StdName],[Email],[Phone],[Address])  
     VALUES ('Afreen','','01030550005','Madurai,India')  
     select * from [StudentMasters]

Now it’s time to create our first ASP.NET Core and Angular4 application.

Step 1- Create ASP.NET Core Empty project

After installing all the prerequisites listed above, click Start >> Programs >> Visual Studio 2017 >> Visual Studio 2017, on your desktop. Click New >> Project. Select Web >> ASP.NET Core Angular 2 Starter. Enter your project name and click OK.

Select Empty Project and click ok, if you have installed ASP.ENT Core 2.0 then you can then chose ASP.NET Core 2.0.

After creating ASP.NET Core Angular 2 application, wait for a few seconds. You can see the empty project was created successfully.

Step 2 – Enabling MVC and StaticFiles
Since we have created as the empty project now we need to enable our project to work with WEB API and also to run the html files for displaying the Angular result we need to enable the StaticFiles.For this right click on your project and click edit your project.csproj.

We can see our csproj file will be opened for edit.

Now add this 2 below code part for enabling the MVC and StaticFile Packages to our project.

<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.2" />
    <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.1" />

Now your code part will be look like below.

Save the csproj file. After saving all the dependency will be installed to our project for working with WEB API.

Step – 3 Working with Database Connections

Adding Connection String

To add the connection string with our SQL connection open the “appsettings.json” file .Yes this is JSON file and this file looks like below Image by default.

In this appsettings.json file add our connection string 

"ConnectionStrings": {
    "DefaultConnection": "Server=YOURDBSERVER;Database=StudentsDB;user id=SQLID;password=SQLPWD;Trusted_Connection=True;MultipleActiveResultSets=true;"

Note change the SQL connection string as per your local connection.

Next step is we create a folder named “Data” to create our model and DBContext and Model class.

Creating Model Class for Student

We can create a model by adding a new class file in our Data Folder. Right Click Data folder and click Add>Click Class. Enter the class name as StudentMasters and click Add.

Now in this class we first create property variable, add student. We will be using this in our WEB API controller.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;

namespace Angular2ASPCORE.Data
    public class StudentMasters
  public int StdID { get; set; }

  [Display(Name = "Name")]
  public string StdName { get; set; }

  [Display(Name = "Email")]
  public string Email { get; set; }

  [Display(Name = "Phone")]
  public string Phone { get; set; }

  public string Address { get; set; }

Creating Database Context

DBContext is Entity Framework Class for establishing connection to database
We can create a DBContext class by adding a new class file in our Data Folder. Right Click Data folder and click Add>Click Class. Enter the class name as ASPNETCOREContext and click Add.

In this class we inherit DbContext and created Dbset for our students table.

public class ASPNETCOREContext : DbContext
 public ASPNETCOREContext(DbContextOptions<ASPNETCOREContext> options)
  : base(options)

 public DbSet<StudentMasters> StudentMasters { get; set; }

Step – 4 Editing Startup.cs file

Open the Startup.cs file

Now in Startup.cs file we need add the MVC DbContext to Service and also to set the default open html page like below.

public void ConfigureServices(IServiceCollection services)

services.AddDbContext<ASPNETCOREContext>(options =>

        // 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)
   app.Use(async (context, next) => {
    await next();
    if (context.Response.StatusCode == 404 &&
     !Path.HasExtension(context.Request.Path.Value) &&
     context.Request.Path = "index.html";
     await next();

Step – 4 Creating Web API

To create our WEB API Controller, right click project folder. Click Add and click New Item.

Select ASP.NET Core >Select Web API Controller Class and click Add

As we all know Web API is a simple and easy way to build HTTP Services for Browsers and Mobiles.

Web API has the following four methods as Get/Post/Put and Delete.

  • Get is to request for the data. (Select)
  • Post is to create a data. (Insert)
  • Put is to update the data.
  • Delete is to delete data.

Here in this demo we are using only the Get method so we can delete all other methods of PUT/POST and Delete from the controller class and in Get Method we return the string values like below.

Get Method(Select Operation)

Get Method is to request single item or list of items from our selected Database. Here we will be get all student information’s from StudentMasters Table.

 public class StudentMastersAPIController : Controller
  private readonly ASPNETCOREContext _context;

  public StudentMastersAPIController(ASPNETCOREContext context)
   _context = context;

  // GET: api/StudentMastersAPI
  public IEnumerable<StudentMasters> GetStudentMasters()
   return _context.StudentMasters;


To test Get Method, we can run our project and copy the get method api path, here we can see our API path for get is api/StudentMastersAPI
Run the program and paste the above API path to test our output.

Step – 5 Working with Angular

Now let’s start working with Angular part.

First, we need to install the Angular CLI to our project

Angular CLI:

Angular cli is a command line interface to scaffold and build angular apps using nodejs style (commonJs) modules. Ref link

To install the Angular CLI to our project open the Visual Studio Command Prompt and move the project folder path.

We need to move to our project folder path. If you not sure about your project path then click on the Project and see the properties to check the project path.

Copy the Project Folder path. Here we can see as my project is in G: drive so first change to G: drive and change to our project folder

Now install the Angular CLI to your project. To Install it write the below command and run it.

npm install @angular/cli --global

Wait for few seconds to Angular CLI install on your project

Now its time to scaffold a Angular application in our project run the below command and wait for few second and you can see all the Angular files will be added in our project.

ng new ASPNETCOREDEMO --skip-install

Note that you need to add your project name after the new keyword from above command. Here my project name is ASPNETCOREDEMO. Runt he above command

Wait for few second and we can see the success message like below.

In our project, we can see a new folder with our same project name has been created.

Open the folder and we can see all the Angular files has been created inside the folder.

Move all the files to the main project

After moving all the files to the main project delete the empty folder.

Step – 6 Working with Angular Files

Working with Angular Module 

.angular-cli.json :

Open angular-cli.json file and change the “outDir” to  wwwroot from dist

Change dist to wwwroot for adding all the angular resultant html and dependency script file to build and update for displaying the result.

Since we need to display the Web API result in our Angular application, we need to import the HTTPmodul in app.module file.

Open the app.module file

Change with the below code

import { BrowserModule } from @angular/platform-browser;
import { NgModule } from @angular/core';

import { AppComponent } from './app.component';
import { FormsModule } from @angular/forms;
import { HttpModule } from @angular/http;
  declarations: [
  imports: [
  providers: [],
  bootstrap: [AppComponent]
export class AppModule { }

Working with Angular Component

Now we need to work with our Angular Component to link with our Web API and get the JSON result to bind in our html file.

Open the Angular Component file and add the below code.

import { Component, OnInit } from @angular/core;
import { Http } from @angular/http
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
export class AppComponent implements OnInit {
    constructor(private _httpService: Http) { }
    title: string = "SHANU";
    apiValues: string[] = [];
    ngOnInit() {
        this._httpService.get('/api/StudentMastersAPI/').subscribe(result => {
            this.studentdetails = result.json() as string[];

Working with HTML FILE

Now we are in the final stage of the coding part, Design our html and bind the result from Angular to your app.component.html file.

Edit the html file and change with this below code.

<h1><span style="color:#285783">Welcome to {{title}} Angular and ASP.NET Core  Demo </span></h1>

<hr />

<table class='table' style="background-color:#FFFFFF; border:2px #6D7B8D; padding:5px;width:99%;table-layout:fixed;" cellpadding="2" cellspacing="2" *ngIf="studentdetails">
    <td width="180" align="center"><strong>STD ID</strong></td>
    <td width="180" align="center"><strong>Name</strong></td>
    <td width="180" align="center"><strong>Email</strong></td>
    <td width="180" align="center"><strong>Phone</strong></td>
    <td width="180" align="center"><strong>Address</strong></td>
  <tbody *ngFor="let std of studentdetails">
      <td align="center" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">
        <span style="color:#9F000F">{{std.stdID}}</span>


      <td align="center" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">
        <span style="color:#9F000F">{{std.stdName}}</span>


      <td align="center" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">
        <span style="color:#9F000F">{{}}</span>


      <td align="center" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">
        <span style="color:#9F000F">{{}}</span>


      <td align="center" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">
        <span style="color:#9F000F">{{std.address}}</span>


Step – 6 Build and Run

First, we need to install all the Angular dependency to our application. To install enter the below command and run in the command prompot.

npm install

Wait till the npm install complete

Build the Application

Enter the below command to build the application

ng build

Wait for few second till the build complete.

Runt the application

Enter the below command and press enter to run the application.

dotnet run

We can see the localhost address to run our application. Enter the address in browser to see our Angular Application running with the result displayed.




Points of Interest

First create the Database and Table in your SQL Server. You can run the SQL Script from this article to create StudentsDB database and StudentMasters Table and also don’t forget to change the Connection string from “appsettings.json”.Build and Run the application to see the result.

History - 2017/09/06


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


About the Author

syed shanu
Team Leader
India India
Microsoft MVP | Code Project MVP | CSharp Corner MVP | Author | Blogger and always happy to Share what he knows to others. MyBlog

My Interview on Microsoft TechNet Wiki Ninja Link

You may also be interested in...


Comments and Discussions

GeneralAutomatic updates Pin
Leonidius16-Sep-17 13:36
memberLeonidius16-Sep-17 13:36 
QuestionHello syed shanu Pin
Member 1340703812-Sep-17 20:02
memberMember 1340703812-Sep-17 20:02 
Questionsome issues Pin
blfuentes5-Sep-17 22:52
memberblfuentes5-Sep-17 22:52 
AnswerRe: some issues Pin
syed shanu6-Sep-17 4:38
mvpsyed shanu6-Sep-17 4:38 

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.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web01-2016 | 2.8.180712.1 | Last Updated 12 Sep 2017
Article Copyright 2017 by syed shanu
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid