ASP.NET Core is a new open-source and cross-platform framework for building cloud-connected applications, similar to web apps for mobile, … . Let's get familiar with ASP.NET Core and Angular 4 through WEB API.
Make sure you have installed the following software on your computer to get acquainted with ASP.NET Core effectively.
1. First, download and install Visual Studio 2017 on your computer from here: Download Visual Studio 2017
2. Download and install .NET Core 1.0.1 from here: Download .NET Core 1.0.1
3. Download and install Node.js v4.0 or higher versions from here: Download Node.js
Choose the workload volume according to your needs and install Visual Studio 2017 on your computer. If Visual Studio 2017 is already installed, you can skip this part.
After the installation is complete, you can open Visual Studio 2017 to create an ASP.NET Core and Angular v4 application.
The next step in getting familiar with ASP.NET Core and Angular 4 through WEB API is to create the initial projects with ASP.NET Core.
Step 1: Create ASP.NET Core Project
After successfully installing the prerequisites mentioned above, on the desktop, click Start =>Programs =>Visual Studio 2017 =>Visual Studio 2017.
Click on New =>Project. Select Web =>ASP.NET Core Web Application. Enter your project name and click OK.
Choose Project Empty and click OK. If you've installed ASP.NET Core 2.0, you can select ASP.NET Core 2.0.
After creating the ASP.NET Core Angular 2 application, wait for a few seconds, and you will see the successfully created empty project.
Step 2: Enable MVC and StaticFiles
In the previous step, you created an empty project. Now, the next step is to activate the project to work with the WEB API and run HTML files. To display Angular results, you need to activate static files.
To do this, right-click on the project, select Edit (your project name).csproj.
Now you can see the .csproj file opened for editing.
Next, add the following two code snippets to activate the corresponding MVC and StaticFile Packages in your project.
Now, your code snippet will look like this:
Save the .csproj file. After completion, the dependencies will be installed in your project to work with the Web API.
Step 3: Edit the Startup.cs file
Firstly, open the file Startup.cs.
Next, within the Startup.cs file, add the MVC Service. Additionally, set default values and open the HTML page as shown below:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
// Configure the HTTP request pipeline in this method called by the runtime.
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: Create Web API
To generate a WEB API Controller, right-click on the project folder, then choose Add =>New Item.
Select ASP.NET Core =>Web API Controller class and click on Add.
As you know, Web API is a simple way to build HTTP Services for browsers and mobile devices.
Web API provides the following 4 methods: Get, Post, Put, and Delete.
- Get is used to request data. (retrieve)
- Post is employed to create new data. (insert)
- Put is utilized to update data.
- Delete is used for data deletion.
In the example below, the Get method is used. Therefore, you can remove all other methods including PUT, POST, and Delete in the Controller class. In the Get method, return a string value as shown below.
The modified Web API Controller class looks like the following:
[Route('api/[controller]')]
public class ValuesController : Controller
{
// Endpoint for GET requests to api/values
[HttpGet]
public IEnumerable
{
return new string[] { 'Afraz', 'Afreen', 'ASHA', 'KATHER', 'Shanu' };
}
}
}
To verify the Get method, run your project and copy the API endpoint. Here, you can see the API endpoint for the Get method is “api/values”.
Run the program and paste the above API endpoint to check the output.
Step 5: Working with Angular
The next step is working with Angular. First, you need to install Angular CLI for the project.
Angular CLI
Angular CLI is a command-line interface for building Angular applications using node.js style modules (commonJS).
To install Angular CLI for your project, open the Visual Studio Command Prompt and navigate to the project directory path.
The next step now is to navigate to the project directory path. If uncertain about the project path, click on Project and check the properties to verify the project path.
Copy the project directory path. In this example, you can see the project is in drive G:. First, change to drive G:, then change to the project folder.
Next, install Angular CLI for your project. To install Angular CLI, run the command below:
npm install @angular/cli -g
Wait for a few seconds for Angular CLI to install in your project.
Now, run the command below and wait a few seconds. All Angular files will be added to the project:
ng new ASPNETCOREDEMO --skip-install
Note that in the command above, replace ASPNETCOREDEMO with the name of your project.
Wait a few seconds until the success message appears as below.
In the project, a new folder will be created with the same name as the project.
Open that folder, and you can see all the Angular files created inside the directory.
Move all the files into the main project.
After moving all the files into the main project, proceed to delete the empty folder.
Step 6: Working with Angular Files
Working with Angular Module
To display the Web API results in the Angular application, you need to import HTTP module in the app.module file.
Open the app.module file.
Replace it with the code below:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Working with Angular Component
The next step now is to work with Angular Component to link with Web API and receive JSON results to bind with HTML file.
Open the Angular Component file and add the code below:
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
This is the final step of the code. Design the HTML and link the Angular results to the app.component.html file.
Edit the HTML file and change it to the following code:
Step 7: Build and Run the Application
First, you need to install all Angular dependencies for the application. To install, run the command below in the command prompt:
npm install
Wait for the NPM installation process to complete.
Build the Application
Run the command below to build the application:
ng build
Wait for a few seconds until the application building process completes.
Run the Application
Enter the command below and press Enter to run the application:
dotnet run
You can find the localhost address to run the application. Enter that address into your browser. The Angular application is now running and displaying the desired results.
Above, Mytour has introduced you to getting started with ASP.NET Core and Angular 4 through WEB API. We hope this article is helpful for you. If you have any questions, feel free to leave your comments below the article.
