Introduction



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

Building the Sample

Prerequisites

Make sure you have installed all the following 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 one depending on your needs and install the Visual Studio 2017 on your computer.

After installing you can open Visual Studio 2017 to create your first ASP.NET Core and Angular4 application.


Description

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 choose ASP.NET Core 2.0.


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

Step 2 – Enabling MVC and StaticFiles

Since we have created it as an empty project we now 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.



Add the following code to enable MVC and add the StaticFile Packages to our project.

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

Now our code will look as in the following:


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

Step – 3 Editing Startup.cs file

Open the Startup.cs file

In the Startup.cs file we need to add the MVC Service and also to set the default open html page like below.
public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }// 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.Value.StartsWith("/api/"))
                {
                    context.Request.Path = "./src/index.html";
                    await next();
                }});
            app.UseMvcWithDefaultRoute();
            app.UseDefaultFiles();
            app.UseStaticFiles();
        }

Step – 4 Creating Web API

To create our WEB API Controller, right click the 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.

Our edited Web API Controller class will look like this:

[Route("api/[controller]")] 
    public class ValuesController : Controller 
    {// GET: api/values 
        [HttpGet] 
        public IEnumerable<string> Get() 
        {returnnew string[] {"Afraz", "Afreen", "ASHA", "KATHER", "Shanu"}; 
        }}}

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 is api/values.

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



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

Now we need to move to our project folder path. If you are 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 that my project is in the G: drive so first change to the G: drive and change to our project folder.

Install the Angular CLI to your project. To install it use the following command and run it.

npm install @angular/cli –global


Wait a few seconds for Angular CLI to install in your project.

Now its time to scaffold an Angular application in our project run the following command and wait a few seconds and you will see that all the Angular files were be added to our project.

ng new ASPNETCOREDEMO --skip-install

Note that you need to add your project name after the new keyword from the preceding command. Here my project name is ASPNETCOREDEMO. Run the above command and wait a few seconds and you will 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 that all the Angular files have 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 

Since we need to display the Web API result in our Angular application, we need to import the HTTPmodul in the 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';
@NgModule({
    declarations: [
        AppComponent
    ],
    imports: [
        BrowserModule,
        FormsModule,
        HttpModule
    ],
    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';
@Component({
    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/values').subscribe(values => {this.apiValues = values.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 the code as in the following:

<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="apiValues">
  <tr>
    <td width="180" align="center"><strong>Names</strong></td>
  </tr>
  <tbody *ngFor="let value of apiValues">
    <tr>
      <td align="center" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">
        <span style="color:#9F000F">{{value}}</span>
  
  
      </td>
    </tr>
  </tbody>
</table>

Step – 6 Build and Run

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

npm install


Wait until the npm has been installed completely.

Build the Application

Enter the below command to build the application.

ng build
Wait for few second till the build complete.

Run 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 the browser to see our Angular Application running with the result displayed.



See Also

Download

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