Angular  

How to Call an ASP.NET Core API from Angular

Calling an ASP.NET Core Web API from an Angular application is a very common and essential task in full-stack development. Angular handles the front-end user interface, while ASP.NET Core manages the server-side logic and database interactions. This guide walks you through the entire process from creating the API endpoint to consuming it inside an Angular application.

1. Create a Simple ASP.NET Core API

Start by creating a new ASP.NET Core Web API project using the CLI or Visual Studio.

1.1 Create the API Project

Using .NET CLI:

dotnet new webapi -n MyApi

Folder structure:

MyApi/
  Controllers/
  Program.cs
  appsettings.json

2. Create an API Endpoint

In the Controllers folder, create a new controller called UsersController.

2.1 Controller Example

using Microsoft.AspNetCore.Mvc;

namespace MyApi.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class UsersController : ControllerBase
    {
        [HttpGet]
        public IActionResult GetUsers()
        {
            var users = new[]
            {
                new { Id = 1, Name = "John Doe" },
                new { Id = 2, Name = "Jane Smith" }
            };

            return Ok(users);
        }
    }
}

This endpoint returns a simple list of users.

3. Enable CORS in ASP.NET Core

Angular runs on a different port (e.g., 4200), so you must allow cross-origin requests.

3.1 Add CORS in Program.cs

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowAngular",
        policy => policy.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
});

builder.Services.AddControllers();

var app = builder.Build();

app.UseCors("AllowAngular");
app.MapControllers();

app.Run();

This allows Angular to call your API successfully.

4. Create Your Angular App

If you do not already have an Angular project, create one.

4.1 Create Angular Project

ng new my-angular-app
cd my-angular-app

5. Create an Angular Service to Call the API

Angular best practice: All API calls go inside services.

5.1 Create the service

ng generate service services/user

This creates:

src/app/services/user.service.ts

5.2 Import HttpClientModule

Open app.module.ts and add:

import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    BrowserModule,
    HttpClientModule
  ]
})
export class AppModule {}

5.3 Add API call to the service

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

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

  private apiUrl = 'https://localhost:5001/api/users';

  constructor(private http: HttpClient) {}

  getUsers(): Observable<any> {
    return this.http.get(this.apiUrl);
  }
}

6. Call the API from an Angular Component

6.1 Create component

ng generate component pages/user-list

6.2 Inject and call the service

Open user-list.component.ts:

import { Component, OnInit } from '@angular/core';
import { UserService } from '../../services/user.service';

@Component({
  selector: 'app-user-list',
  templateUrl: './user-list.component.html'
})
export class UserListComponent implements OnInit {

  users: any[] = [];

  constructor(private userService: UserService) {}

  ngOnInit(): void {
    this.loadUsers();
  }

  loadUsers() {
    this.userService.getUsers().subscribe(data => {
      this.users = data;
    });
  }
}

6.3 Display data in HTML

Open user-list.component.html:

<h3>User List</h3>

<ul>
  <li *ngFor="let user of users">
    {{ user.id }} - {{ user.name }}
  </li>
</ul>

7. Test the API Call

7.1 Run the API

dotnet run

API URL example:

https://localhost:5001/api/users

7.2 Run Angular App

ng serve

Open:

http://localhost:4200

You should now see the list of users returned from ASP.NET Core.

8. Common Issues and Solutions

8.1 CORS Error

If you see:

Access-Control-Allow-Origin error

Make sure CORS is enabled in Program.cs and that Angular URL is allowed.

8.2 SSL Certificate Problem

If HTTPS causes issues, change API URL to HTTP:

http://localhost:5000/api/users

8.3 Wrong API URL

Always test the URL in the browser or Postman first.

9. Handling POST Requests

Here is how to send data from Angular to ASP.NET Core.

9.1 API Endpoint in Controller

[HttpPost]
public IActionResult AddUser([FromBody] UserModel user)
{
    return Ok(new { Message = "User added", Data = user });
}

9.2 Angular Service

addUser(user: any): Observable<any> {
  return this.http.post(this.apiUrl, user);
}

9.3 Angular Component Example

addNewUser() {
  const user = { id: 3, name: 'New User' };
  this.userService.addUser(user).subscribe(response => {
    console.log('Added:', response);
  });
}

10. Folder Structure Suggested for Angular Projects

src/
  app/
    services/
      user.service.ts
    pages/
      user-list/
        user-list.component.ts
    app.module.ts

Keeping a clean structure makes your API integration easier to maintain.

11. Summary

Below is what you completed step by step:

  1. Created an ASP.NET Core API.

  2. Added a controller with an endpoint.

  3. Enabled CORS.

  4. Created an Angular app.

  5. Created a service to call the API.

  6. Injected the service in a component.

  7. Displayed API response on the page.

  8. Tested everything.

You now have a working Angular front-end calling an ASP.NET Core back-end using HttpClient.