Single Page Application using Asp.Net Core 2.2 and Angular

Single Page Application using Asp.Net Core 2.2 and Angular

In this blog post, we are going to create Single Page Application (spa) using Asp.Net Core 2.2 and Angular. Microsoft has recently announce the release of Asp.Net Core 2.2.&nbsp;.NET Core 2.2 is supported by&nbsp;<a href="https://visualstudio.microsoft.com/vs/" target="_blank">Visual Studio 15.9</a>, Visual Studio for Mac and Visual Studio Code.

In this blog post, we are going to create Single Page Application (spa) using Asp.Net Core 2.2 and Angular. Microsoft has recently announce the release of Asp.Net Core 2.2. .NET Core 2.2 is supported by Visual Studio 15.9, Visual Studio for Mac and Visual Studio Code.

Download

Download the .Net Core 2.2 SDK from below link, if you don’t have in your machine.

Download the .Net Core 2.2 SDK – Mac OS x64 Installer

Run

Run the downloaded Installer

Finish Installation

After all these steps, this setup has installed Microsoft .Net Core SDK 2.2 successfully on your MacOS. The following packages have been installed on your MacOS with this installer.

  • .Net Core SDK 2.2.101
  • .Net Core Runtime 2.2.0
  • Asp.Net Core Runtime 2.2.0

    Verify Installation

Check the Installation by running these commands in your terminal window.

dotnet Or dotnet –version Let’s create our Angular app in .Net Core 2.2. We are going to use Visual Studio Core on MacOS. If you don’t have Visual Studio Core, you can download from below link.

Download Visual Studio Core

Create Angular App

Moving forward, let’s create our Angular app using the below command in terminal window. I have created a AngularDemo directory, and run the command inside this directory.

cd angulardemo*> *dotnet new angular -o zeptoapp After running this command, it will create Visual studio .csproj file in your folder.

Open the Visual Studio Core IDE, and open the zeptoapp folder. It looks like this.

This project template create an ASP.NET Core app and Angular app. You can use ASP.NET Core app for data access, authorization, and other server-side functionalities.

Your Angular App is inside the ClientApp folder.

Run Angular app

Now, go to clientapp->src folder, and try to run your Angular app by this command in terminal.

ng serve –open Note:- If you see this error message in your console. Could not find module “@angular-devkit/build-angular” from “/Users/XXX/Documents/AngularDemo/zeptoapp/ClientApp”.> Error: Could not find module “@angular-devkit/build-angular” from “/Users/XXX/Documents/AngularDemo/zeptoapp/ClientApp”.> *at Object.resolve (/usr/local/lib/node_modules/@angular/cli/node_modules/@angular-devkit/core/node/resolve.js:141:11)> *at Observable.rxjs_1.Observable *[as _subscribe](https://www.zeptobook.com/usr/local/lib/node_modules/@angular/cli/node_modules/@angular-devkit/architect/src/architect.js:132:40 "as _subscribe*")> at Observable._trySubscribe (/usr/local/lib/node_modules/@angular/cli/node_modules/rxjs/internal/Observable.js:44:25)> at Observable.subscribe (/usr/local/lib/node_modules/@angular/cli/node_modules/rxjs/internal/Observable.js:30:22)> at /usr/local/lib/node_modules/@angular/cli/node_modules/rxjs/internal/Observable.js:99:19> *at new Promise ()> *at Observable.toPromise (/usr/local/lib/node_modules/@angular/cli/node_modules/rxjs/internal/Observable.js:97:16)> *at ServeCommand.initialize (/usr/local/lib/node_modules/@angular/cli/models/architect-command.js:91:94)> *at *> *at process._tickCallback (internal/process/next_tick.js:188:7) Run this npm command in your terminal. npm install –save-dev @angular-devkit/build-angular Once this @angular-devkit has been installed in your project folder, you are now good to go. Now, run your Angular app using ng serve –open

This will successfully launch Angular app at http://localhost:4200/

Run Asp.net Core api with Angular app

Run the complete project. Go to Debug->Start Debugging or Pressing F5, your Angular app and .Net Core app will run altogether.

                                                                                Home Screen

                                                                                 Counter Screen

                                                                         Fetch Data Screen

If you look at the Fetch Data screen, you will be wondering how this data is coming, as we haven’t created any Angular component or service to display the data. This is the magic of .Net Core with Angular. We got everything setup for us. Let’s look into the details of each section.

Let’s first look at out .Net Core Controller API code.

SampleDataController.cs

You can see, our have SampleDataController.cs file in Controllers folder of our project. In the controller file, we have code for our Fetch Data page.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace zeptoapp.Controllers
{
    [Route("api/[controller]")]
    public class SampleDataController : Controller
    {
        private static string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        [HttpGet("[action]")]
        public IEnumerable<WeatherForecast> WeatherForecasts()
        {
            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                DateFormatted = DateTime.Now.AddDays(index).ToString("d"),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            });
        }

        public class WeatherForecast
        {
            public string DateFormatted { get; set; }
            public int TemperatureC { get; set; }
            public string Summary { get; set; }

            public int TemperatureF
            {
                get
                {
                    return 32 + (int)(TemperatureC / 0.5556);
                }
            }
        }
    }
}

Now, look at the Angular component in our project solution.

                                                  import { Component, Inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-fetch-data',
  templateUrl: './fetch-data.component.html'
})
export class FetchDataComponent {
  public forecasts: WeatherForecast[];

  constructor(http: HttpClient, @Inject('BASE_URL') baseUrl: string) {
    http.get<WeatherForecast[]>(baseUrl + 'api/SampleData/WeatherForecasts').subscribe(result => {
      this.forecasts = result;
    }, error => console.error(error));
  }
}

interface WeatherForecast {
  dateFormatted: string;
  temperatureC: number;
  temperatureF: number;
  summary: string;
}
<h1>Weather forecast</h1>

<p>This component demonstrates fetching data from the server.</p>

<p *ngIf="!forecasts"><em>Loading...</em></p>

<table class='table table-striped' *ngIf="forecasts">
  <thead>
    <tr>
      <th>Date</th>
      <th>Temp. (C)</th>
      <th>Temp. (F)</th>
      <th>Summary</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let forecast of forecasts">
      <td>{{ forecast.dateFormatted }}</td>
      <td>{{ forecast.temperatureC }}</td>
      <td>{{ forecast.temperatureF }}</td>
      <td>{{ forecast.summary }}</td>
    </tr>
  </tbody>
</table>

Run Angular app Independently

The project is configured to start its own instance of the Angular CLI server in the background when the ASP.NET Core app starts in development mode. This is convenient because you don’t have to run a separate server manually.

There’s a drawback to this default setup. Each time you modify your C# code and your ASP.NET Core app needs to restart, the Angular CLI server restarts. Around 10 seconds is required to start back up. If you’re making frequent C# code edits and don’t want to wait for Angular CLI to restart, run the Angular CLI server externally, independently of the ASP.NET Core process. To do so:

  • In terminal, go to ClientApp folder, and run this command.

    npm start** Modify your ASP.NET Core app to use the external Angular CLI instance instead of launching one of its own. In your *Startup class, replace the spa.UseAngularCliServer invocation with the following: spa.UseProxyToSpaDevelopmentServer(“*http://localhost:4200”);; "http://localhost:4200”);*") When you start your ASP.NET Core app, it won’t launch an Angular CLI server. The instance you started manually is used instead. This enables it to start and restart faster. It’s no longer waiting for Angular CLI to rebuild your client app each time.

    Summary

In summary, we have learned how to create a single page application using Asp.Net core as backend and Angular as frontend. This is more productive, flexible and less time consuming process.

asp.net angular

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Hire ASP.Net Developers

Looking to outsource your asp dot net development requirement? ASP.Net is a special feature of the DOT Net framework created by Microsoft. At [HourlyDeveloper.io](https://hourlydeveloper.io/ "HourlyDeveloper.io"), we have a team of experienced...

Angular 9 CRUD with ASP.NET Core Web API

Implement CRUD Operations in Angular with ASP.NET Core Web API. To demonstrate this topic we've build a project form scratch.In this article, we’ll implement Asp.Net Core 3.0 Web API CRUD Operations with Angular 9. To demonstrate the topic, we’ll build a project from scratch with payment details like Credit/ Debit Card.

Routing in MVC - ASP.NET Core Demystified

ASP.NET Core MVC has introduced quite a few concepts that new (or new-to-ASP.NET) web developers might have some difficulty getting caught up with. My ASP.NET Core Demystified series is designed to help these developers get started building their own custom, full-fledged, working AASP.NET Core applications. In

What is the ASP.Net Machine Account on my Computer?

Some users have reported the existence of the ASP.Net machine account. In this article, I will discuss what is asp.net machine account in windows 10/7 and how to disable it, asp.net machine account password, and can I delete asp.net machine account? .NET Framework is an application on Windows that requires the installation to run several apps or games. However, when the .NET Framework is downloaded and installed, the application automatically creates an ASP NET machine account.

Angular and ASP.NET Core

​ The&nbsp;[Angular CLI](https://cli.angular.io/ "Angular CLI")&nbsp;provides a way to develop front-end applications using angular that hides a lot of details. For example there's no requirement to understand how&nbsp;[Webpack](https://webpack.js.org/ "Webpack")&nbsp;or&nbsp;[SystemJS](https://github.com/systemjs/systemjs "SystemJS")&nbsp;work. ​ In fact, if you don't know a little bit about Webpack, which is what is used to build the latest version of Angular applications, the CLI almost looks like magic. You just need to do a&nbsp;ng new&nbsp;and&nbsp;ng serve --open&nbsp;and you have a working Angular application open in your web browser. ​ The fact that the CLI hides all the plumbing might lead to questions like: "How do I use Angular with ASP.NET Core?". ​ ![](https://res.cloudinary.com/practicaldev/image/fetch/s--dKBafg3O--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/http://www.blinkingcaret.com/wp-content/uploads/2018/01/asp_net_core_and_angular_logo.png) ​ I hope that by the end of this blog post it will be clear to you how you can answer that question (and not only with ASP.NET Core, with whichever technology you want to use your Angular app with). ​ You see, an angular app is an app in and of itself, it does need to be "served" somehow by a web server. ​ When you compile an angular application you are producing a set of JavaScript, CSS and one index.html file. That's it. ​ The default folder where those "artifacts" get copied to is&nbsp;yourApplicationFolder/dist. You can check it out by going to your Angular application and doing an&nbsp;ng build. ​ Go on, I'll wait. ​ When you do&nbsp;ng serve --open&nbsp;you are actually using a stand-alone web server ([webpack-dev-server](https://github.com/webpack/webpack-dev-server "webpack-dev-server")) to serve that index.html file in the dist folder. ​ The rest of this blog post will describe several approaches that you can take for using Angular with ASP.NET Core. The first is to have ASP.NET Core serve the Angular files. ​ The second approach is to have Angular and ASP.NET Core as different applications. There's an example of how to achieve this using Nginx where both Angular and ASP.NET Core are served using port 80 and in IIS where each application is served from its own port. ​ The final part of the post describes a setup that I consider ideal where you can use Angular's&nbsp;ng serve&nbsp;during development. ​ This post is quite long but the sections are fairly independent. If your are only interested in the last section and you are using Windows I recommend also reading the section on how to configure Angular in IIS. ## Using ASP.NET Core to serve the Angular application ​ It can be argued that serving an Angular application "within" ASP.NET Core is wasteful in terms of resources. In the end the Angular application is just a set of static files, there's no need to have the request for those files go through the ASP.NET Core middleware pipeline. ​ There might be some good reasons for doing it though, also there's no harm in knowing how to do it and since it seems to be a common approach, being familiar with it might be useful. ​ One important thing to know in order to understand how we can serve an ASP.NET Core and Angular application together is to understand how a request is processed in ASP.NET Core. ​ When you run an ASP.NET Core application your request goes through a "pipeline" of&nbsp;[middlewares](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware?tabs=aspnetcore2x "middlewares"). Every time a request comes in it goes through the middlewares in the order they are defined, and then in reverse order. ​ Every middleware has an opportunity to change the request or response two times, once before the other middlewares have been executed, and then after the other middlewares have executed. This allows for a middleware at the top of the pipeline to handle for example, a 401 response set by a middleware further down in the pipeline. ​ An example of this are the authentication middlewares that change a 401 response to a 302 redirect to a login page. The Angular CLI provides a way to develop front-end applications using angular that hides a lot of details. For example there’s no requirement to understand how Webpack or SystemJS work.