Create a web application using ASP.NET Core and Angular

Introduction

In this article, we are going to create a web application using ASP.NET Core MVC and Angular with Visual Studio 2017. We will be creating a sample application and performing some operations on it.

Prerequisites

The requirements you need to have these 4 installed on your system

1] Node

2] NPM

npm install -g npm

3] Visual Studio 2017

4] Dotnet core 2.0.5

Create Project

Let’s go to the Visual Studio and click on the File > New Project, and choose ASP.NET Core Web Application then choose version 2.0. since we want to use .NET Core and the application name is AngularWithCore.

Create Asp.net core with angular template

Add template in project

you can see here, we have the asp.net core 2.0 selected views the empty project.

asp.net core select empty view project

We’ve got our Project files.

asp.net core project structure

Let’s Build and Run the project and see the output.

ASP.NET MVC localhost output

Let’s a go-to visual studio and update the .csproj file and select your project name then Right click and open folder and file explorer. here is our project structure and see the .csproj file.

We already have Microsoft.AspNetCore.All installed, we should add two more packages let’s add reference include Microsoft.AspNetCore.MVC 2.0.2 and the second package include Microsoft.AspNetCore.StaticFiles version 2.0

<Project Sdk="Microsoft.NET.Sdk.web">
  <PropertyGroup>
    <TargetFramework>netcoreaoo2.0</TargetFramework>
      </PropertyGroup>
      <ItemGroup>
     <Folder Include="wwwroot">
     </ItemGroup>
     <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.all" Version="2.0.5" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.0.2" />
    <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="2.0.2" />
  </ItemGroup>
</Project>

Restore project dependencies

The project folder, we should run dotnet restore to add those two newly added packages.

>> dotnet restore

Middleware

Let’s go and open startup.cs file that you see we’ve got two methods here ConfigureServices and Configure methods.

public class Startup   
{  
    public void ConfigureServices(IServiceCollection services)  
    {  
       services.AddMvc();
    }  
    public void Configure(IApplicationBuilder app)  
    {  
      if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
    }
    else
    {
        app.UseExceptionHandler("/Error");
    }
	app.Use(async (context, next) => {
	await next();
	if (context.Response.StatusCode == 404 &&
	!Path.HasExtension(context.Request.Path.value)&&
	!context.Request.Path.Value.StartWith("/api/"))
	{
	  context.Request.Path = "/index.html";
	  await next();
	}
	});
	app.UseMvcWithDefaultRoute();
	app.UseDefaultFiles();
        app.UseStaticFiles();
    }         
}

In the configure services, we should add MVC middleware and in the configure method. we should add the default MVC route and default files and static files.

Adding Controller

Let’s add a Controllers folder to our application and right-click on controllers folder and Add a new testController class.

create controller in asp.net core project

In the controller class, we import the namespace, and let’s add a route to the class route and we want this route to be an API controller. then add a method it should be a public method and the output of this method is an array of a string so we use IEnumerable of a string.

namespace AngularWithCore.Controllers
{
    [Route("api/[controller]")]
    public class testController : Controller
    {
        // GET: api/values
        [HttpGet("/api/values")]
        public IEnumerable<string> Get()
        {
            return new string[] {"Walter","Jack","Sam","Rick"};
        }
     }
}

Let’s add an attribute binding since we want to get the info we use HttpGet attribute.

We can directly run the app using PowerShell.

dotnet run command in asp.net mvc core

Now it listening on localhost and then open the browser and see the output works fine.

asp.net core API Get method

Add Angular App in our Project

Let’s go to the next step and add the actual angular application to our project. first, go to the PowerShell control and we should install the NPM packages globally.

Creating project using CLI

After the NPM packages loading add the actual angular project and for we use ng new and the name of the project. following angular CLI command

npm install -g angular-cli

The angular project created and it’s installing the packages for tooling.

angular cli generate project on commanline

Project Structure

Inside the AngularProject folder, we’ve got the e2e folder and source files source folder which contains the app assets environment and we should wait until it finishes installing packages it may take a few minutes.

You see here we’ve got a node_modules folder which contains all the required angular packages

npm node modules  packages

We should open this angular-cli.json and on the line outDir or output directory. It is set to dist folder, we should change it to wwwroot and save the file. this is because by default ASP MVC uses only wwwroot folder to serve static files.

"project": {
    "name": "angular-project"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "wwwroot",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.app.json",
      "testTsconfig": "tsconfig.spec.json",
      "prefix": "app",
      "styles": [
        "styles.css"
       ]
}

Root Module

Then let’s go to the app folder and app.module.ts and we make sure we have we’ve got this HTTP module here.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
// ...

@NgModule({
  // ...
  declarations: [
  AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
    // ...
  ],
  providers: [],

  // ...
})
export class AppModule { }

The API from angular and we should go to the app folder and app.component.ts since is the starting point in the project before we do anything we should import HTTP from angular HTTP package so we can call the service.

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 _service:http) { }

  ngOnInit() {
   this._service.get("/api/values").subscribe(result =>
   this.apiValues = result.json() as string[];
  }});
}

We imported HTTP to get the service we called the service in the constructor we called it _service and in ngOnInit() we called the service using the Get method and the API route subscribe to the result and convert it to JSON and a string array.

Let’s create the HTML component app.component.html and we should iterate through this result and get the values.

We use the string interpolation and here saved resolved.

<h1> Angular with asp.net core</h1>
<ul>
 <li *ngFor="let result of apiValues">{{result}}</li>
</ui>

Build Project using CLI

Let’s go to PowerShell and enter Commandng build to build the project.

ng build in angular cli

Here building the project and its modules. you can see here.

building the project and its module in angular cli

Run Application

Let’s run the application and go to the PowerShell command and make sure you’re inside the directory of your project and we run the Dotnet run command and build the project.

>> dotnet run

You can see here, it listening on HTTP localhost and here we’ve got the output of our project.

Thanks for the Reading article! I hope this get’s you started application using ASP.NET Core using Angular. Take care.

Leave a Reply

Your email address will not be published. Required fields are marked *