Getting Started With ASP.NET Core And Angular 4 Using WEB API

ASP.NET Core

Introduction

In this article, let’s see how to get started with ASP.NET Core using Web API. Please read my previous articles which explain in-depth about getting started with ASP.NET Core Template Pack.

Prerequisites

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).

    ASP.NET Core

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


ASP.NET Core

Once installed, you can open the Visual Studio 2017 to create your first ASP.NET Core and Angular v4 application.

ASP.NET Core

Code Part

Now, it’s time to create our first ASP.NET Core and Angular v4 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 Web Application. Enter your project name and click OK.

ASP.NET Core

Select Empty Project and click OK. If you have installed ASP.NET Core 2.0, then you can chose ASP.NET Core 2.0.

ASP.NET Core

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

ASP.NET Core

Step 2 – Enabling MVC and StaticFiles

Since we have created 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 static files.

For this, right click on your project and click Edit (your project name).csproj.

ASP.NET Core

We can see that our .csproj file is opened for editing.

ASP.NET Core

Now, add these 2 below code parts for enabling the MVC and StaticFile Packages respectively within your project.

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

Now, your code part will look like below.

ASP.NET Core

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

Step – 4 Editing Startup.cs file

Open the Startup.cs file

ASP.NET Core

Now, in Startup.cs file, we need to add the MVC Service. Also to set it as default, open the HTML page like below.

  1. public void ConfigureServices(IServiceCollection services)  
  2.         {  
  3.             services.AddMvc();  
  4.         }  
  5.   
  6.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  7.         public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)  
  8.         {  
  9.             app.Use(async (context, next) => {  
  10.                 await next();  
  11.                 if (context.Response.StatusCode == 404 &&  
  12.                     !Path.HasExtension(context.Request.Path.Value) &&  
  13.                     !context.Request.Path.Value.StartsWith("/api/"))  
  14.                 {  
  15.                     context.Request.Path = "./src/index.html";  
  16.                     await next();  
  17.                 }  
  18.             });  
  19.             app.UseMvcWithDefaultRoute();  
  20.             app.UseDefaultFiles();  
  21.             app.UseStaticFiles();  
  22.         }  

Step – 5 Creating Web API

To create the WEB API Controller, right click project folder. Click Add >> New Item.

ASP.NET Core

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

ASP.NET Core

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 - 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.

Our edited Web API Controller class will look like this.

  1. [Route("api/[controller]")]  
  2.     public class ValuesController : Controller  
  3.     {  
  4.         // GET: api/values  
  5.         [HttpGet]  
  6.         public IEnumerable<string> Get()  
  7.         {  
  8.             return new string[] { "Afraz""Afreen""ASHA""KATHER""Shanu" };  
  9.         }  
  10.     }  
  11. }   

To test the Get method, we can run our project and copy the get method API path. Here, we can see our API path for Get, which is "api/values".

Run the program and paste the above API path to test the output.

ASP.NET Core

Step – 5 Working with Angular

Now, let’s start working with the 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 node.js style (commonJS) modules. Ref link

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

ASP.NET Core

Now, we need to move to our project folder path. If you are not sure of your project path, then click on the Project and see the properties to check the project path.

ASP.NET Core

Copy the project folder path. Here, you can see that my project is in G: drive. So first, change to G: drive and then let's change to our project folder.

ASP.NET Core

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

npm install @angular/cli –global

ASP.NET Core

Wait for a few seconds for Angular CLI getting installed on your project.

ASP.NET Core

Now, it's time to scaffold an Angular application in our project. Run the below command and wait for a few seconds. All the Angular files will be added in our project.

ng new ASPNETCOREDEMO --skip-install

Please note that you need to add your project name after the new keyword from the above command. Here, my project name is ASPNETCOREDEMO. Run the above command.

ASP.NET Core

Wait for a few seconds for the success message like below.

ASP.NET Core

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

ASP.NET Core

Open the folder. We can see that all the Angular files have been created inside the folder.

ASP.NET Core


ASP.NET Core

Move all the files to the main project.

ASP.NET Core

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

Step – 6 Working with Angular Files

Working with Angular Module 

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.

ASP.NET Core

Change with the below code.

  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  3.   
  4. import { AppComponent } from './app.component';  
  5. import { FormsModule } from '@angular/forms';  
  6. import { HttpModule } from '@angular/http';  
  7. @NgModule({  
  8.     declarations: [  
  9.         AppComponent  
  10.     ],  
  11.     imports: [  
  12.         BrowserModule,  
  13.         FormsModule,  
  14.         HttpModule  
  15.     ],  
  16.     providers: [],  
  17.     bootstrap: [AppComponent]  
  18. })  
  19. 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.

  1. import { Component, OnInit } from '@angular/core';  
  2.   
  3. import { Http } from '@angular/http';  
  4. @Component({  
  5.     selector: 'app-root',  
  6.     templateUrl: './app.component.html',  
  7.     styleUrls: ['./app.component.css']  
  8. })  
  9. export class AppComponent implements OnInit {  
  10.     constructor(private _httpService: Http) { }  
  11.     title: string = "SHANU";  
  12.     apiValues: string[] = [];  
  13.     ngOnInit() {  
  14.         this._httpService.get('/api/values').subscribe(values => {  
  15.             this.apiValues = values.json() as string[];  
  16.         });  
  17.     }  
  18. }  

Working with HTML FILE

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

Edit the HTML file and change with this below code.

  1. <h1><span style="color:#285783">Welcome to {{title}} Angular and ASP.NET Core  Demo </span></h1>  
  2.   
  3. <hr />  
  4. <table class='table' style="background-color:#FFFFFF; border:2px #6D7B8D; padding:5px;width:99%;table-layout:fixed;" cellpadding="2" cellspacing="2" *ngIf="apiValues">  
  5.   <tr>  
  6.     <td width="180" align="center"><strong>Names</strong></td>  
  7.   </tr>  
  8.   <tbody *ngFor="let value of apiValues">  
  9.     <tr>  
  10.       <td align="center" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">  
  11.         <span style="color:#9F000F">{{value}}</span>  
  12.   
  13.   
  14.       </td>  
  15.     </tr>  
  16.   </tbody>  
  17. </table>  

Step – 6 Build and Run

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

npm install

ASP.NET Core

Wait till the npm installation completes.

ASP.NET Core

Build the Application

Enter the below command to build the application.

ng build

ASP.NET Core

Wait for a few seconds till the build completes.

ASP.NET Core

Run the application

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

dotnet run

ASP.NET Core

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

ASP.NET Core

Conclusion

I hope you liked this article. In my next post, I will show how to get the data from database and display using ASP.NET Core, Angular v4, and Web API.