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.
- First, download and install Visual Studio 2017 from this link.
- Download and install .NET Core 1.0.1.
- Download and install Node.js v4.0 or above. I have installed V6.11.2 (Download link).
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.
Once installed, you can open the Visual Studio 2017 to create your first ASP.NET Core and Angular v4 application.
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.
Select Empty Project and click OK. If you have installed ASP.NET Core 2.0, then you can chose ASP.NET Core 2.0.
After creating ASP.NET Core Angular 2 application, wait for a few seconds. You can see that the empty project is created successfully.
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.
We can see that our .csproj file is opened for editing.
Now, add these 2 below code parts for enabling the MVC and StaticFile Packages respectively within your project.
- <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.2" />
- <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.1" />
Now, your code part will look like below.
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
Now, in Startup.cs file, we need to add the MVC Service. Also to set it as default, open the HTML page like below.
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddMvc();
- }
-
-
- 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 – 5 Creating Web API
To create the WEB API Controller, right click project folder. Click Add >> New Item.
Select ASP.NET Core >> 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 - 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
- {
-
- [HttpGet]
- public IEnumerable<string> Get()
- {
- return new 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, which is "api/values".
Run the program and paste the above API path to test the 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 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.
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.
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.
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 a few seconds for Angular CLI getting installed on your project.
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.
Wait for a few seconds for the success message like below.
In our project, a new folder with our same project name has been created.
Open the folder. 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 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 your 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="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 below command and run in the command prompt.
npm install
Wait till the npm installation completes.
Build the Application
Enter the below command to build the application.
ng build
Wait for a few seconds till the build completes.
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. Our Angular application is running with the desired result displayed.
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.