Connecting Angular with ASP.NET Core

Posted on by Roger Versluis.

Introduction

We will connect Angular and ASP.NET Core and create a test API call.

Connecting .NET Core

Open the ASP.NET Core server solution in Visual Studio, right click the server project and click Properties. Browse to the Debug tab and change the App URL parameter to http://localhost:5000. Now save and close the properties page. This will make sure that IIS Express will listen on port 5000.

Now open Startup.cs and find the line app.UseHttpsRedirection();. Move this line in the if (env.IsDevelopment()) else statement so requests won’t be redirected to HTTPS when doing development work. The Configure method should look like:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseHttpsRedirection();
        app.UseHsts();
    }

    app.UseMvc();
}

Find the ValuesController.cs file in the Controller folder and delete it.

Add a new file called RandomGeneratorController.cs.

We will expose a single API function called Generate.

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

namespace server.Controllers
{
    [Route("/api/RandomNumber")]
    public class RandomGeneratorController : Controller
    {
        [HttpGet]
        [Route("Generate")]
        public ActionResult<Int32> Generate()
        {
            var r = new Random();
            return r.Next(0, 1000);
        }
    }
}

The Route attribute on the top of the class ensures that all routes in the controller are prefixed with /api/RandomNumber.

Now run the project and browse to http://localhost:5000/api/RandomNumber/Generate, every time you refresh the page you will see a new random number between 0 and 1000.

Connecting Angular

Open the Angular project in VSCode and add a new file in the root called angular-proxy.json and add the following contents:

{
    "/api": {
        "target": "http://localhost:5000",
        "secure": false
    }
}

Open angular.json and find the following section:

"serve": {
  "builder": "@angular-devkit/build-angular:dev-server",
  "options": {
    "browserTarget": "client:build"
  },
  "configurations": {
    "production": {
      "browserTarget": "client:build:production"
    }
  }
},

and add the following line below browserTarget:

"proxyConfig": "angular-proxy.json"

The section will look like:

"serve": {
  "builder": "@angular-devkit/build-angular:dev-server",
  "options": {
    "browserTarget": "client:build"
  },
  "configurations": {
    "production": {
      "browserTarget": "client:build:production",
      "proxyConfig": "angular-proxy.json"
    }
  }
},

What this will do is proxy any calls to /api to http://localhost:5000/api.

To be able to use Angulars HttpClient library we have to import it in our AppModule. Open app.module.ts and add HttpClientModule to the @NgModule.imports array. Then add import { HttpClientModule } from '@angular/common/http'; to the top of the page.

We will create a new service which will make a call to the server and generate a random number for us.

Start by generating a new service with ng-cli: ng g s random-number-generator This will create a new service in the file random-number-generator.service.ts.

Now we will add some body to this service. We will want to make a function called generate which calls the server API function at the URL /api/RandomNumber/Generate and returns an observable with an numerical body.

Something like this:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class RandomNumberGeneratorService {

  constructor(private http: HttpClient) { }

  public generate(): Observable<number> {
    return this.http.get<number>('/api/RandomNumber/Generate');
  }
}

Open the random-number.component.ts file and add the RandomNumberGeneratorService to the constructor. Then replace the generate function with the call to generate in the service:

import { Component, OnInit } from '@angular/core';
import { RandomNumberGeneratorService } from '../random-number-generator.service';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-random-number',
  templateUrl: './random-number.component.html',
  styleUrls: ['./random-number.component.scss']
})
export class RandomNumberComponent implements OnInit {

  public randomNumber: Observable<number>;

  constructor(private randomNumberGenerator: RandomNumberGeneratorService) { }

  ngOnInit() {
  }

  public generate(): void {
    this.randomNumber = this.randomNumberGenerator.generate();
  }
}

Because the variable randomNumber now holds an Observable we will have to add the async pipe to random-number.component.html:

<div class="content-container">
  <div class="content-area">
    <h1>Press to generate a random number</h1>
    <button (click)="generate();">Generate</button>
    <h2>{{randomNumber | async}}</h2>
  </div>
</div>

This will ensure that the variable randomNumber isn’t shown until the observable is resolved.

Now run ng serve and go to the Random Number page. Every time you press Generate is will show a new number!

Conclusion

In this article we setup Angular and Visual Studio so they are able to communicate with each other. The test API number generator is an easy way to make sure everything works well. In the next article we will look into adding authentication.