ASP.NET Core  

How to Pass Data Between Angular and ASP.NET Core API

A Simple and Complete Guide for Web Developers

Modern web applications are often built using two main parts:

  1. Frontend – usually written in frameworks like Angular

  2. Backend API – often written in ASP.NET Core

These two layers need to communicate constantly. Angular sends data to ASP.NET Core through HTTP requests, and the API sends data back. This communication allows the application to log in users, load products, submit forms, or display dashboards.

In this article, you will learn in simple language:

  • How Angular sends data to an ASP.NET Core API

  • How ASP.NET Core receives and returns data

  • How to use GET, POST, PUT, and DELETE methods correctly

  • How to pass objects, arrays, query parameters, and route parameters

  • How to secure communication

  • How to test communication with tools like Postman

  • Common mistakes and solutions

Let’s begin.

How Angular Communicates With ASP.NET Core

Modern web applications use HTTP requests to pass data between the frontend and backend. Angular sends requests such as:

  • GET

  • POST

  • PUT

  • DELETE

ASP.NET Core receives the request, processes the data, and returns a JSON response.

Example Flow

  1. Angular builds a request.

  2. Sends it to API endpoint like /api/products.

  3. ASP.NET Core receives the data.

  4. ASP.NET Core returns a response such as JSON.

  5. Angular displays that data on the screen.

All communication happens in JSON, which is easy to read and supported natively in both Angular and ASP.NET Core.

Setting Up ASP.NET Core API

Let us start by creating a simple ASP.NET Core API controller.

Example Model

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

Example API Controller

[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    [HttpGet]
    public IActionResult GetProducts()
    {
        var products = new List<Product>
        {
            new Product { Id = 1, Name = "Laptop", Price = 1200 },
            new Product { Id = 2, Name = "Mouse", Price = 25 }
        };

        return Ok(products);
    }

    [HttpPost]
    public IActionResult AddProduct(Product product)
    {
        // Save to database in real applications
        return Ok(new { Message = "Product received", Received = product });
    }
}

This simple controller supports:

  • GET to retrieve data

  • POST to send data

Now we connect it to Angular.

Setting Up Angular Service to Call the API

In Angular, passing data to an API is usually done in a service using the HttpClient module.

Step 1: Import HttpClientModule

In app.module.ts:

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

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

Step 2: Create a Service

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

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

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

  constructor(private http: HttpClient) { }

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

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

Now Angular can send and receive data.

Passing Data with GET (Fetching Data)

GET is used for retrieving data from the server.

Angular Component

this.productService.getProducts().subscribe(result => {
  this.products = result;
});

ASP.NET Core

Receives GET request in:

[HttpGet]
public IActionResult GetProducts()

Output

Angular prints the list of products on the page.

Passing Data with POST (Sending Data)

POST is used when sending data (form submission, registration, adding products, etc.)

Angular Component (Sending Data)

const newProduct = {
  id: 3,
  name: 'Keyboard',
  price: 45
};

this.productService.addProduct(newProduct).subscribe(result => {
  console.log('Response:', result);
});

ASP.NET Core Receives the Data

[HttpPost]
public IActionResult AddProduct(Product product)
{
    return Ok(product);  // Respond back with the received data
}

The ASP.NET Core API automatically converts JSON sent from Angular into a C# object because of model binding.

Passing Route Parameters (Example: GET by Id)

You often need to pass values inside the URL, for example:

/api/products/5

ASP.NET Core Route

[HttpGet("{id}")]
public IActionResult GetProduct(int id)
{
    return Ok(new { Id = id, Name = "Product Sample" });
}

Angular Service

getProductById(id: number): Observable<any> {
  return this.http.get(`${this.apiUrl}/${id}`);
}

Angular Component

this.productService.getProductById(5).subscribe(result => {
  console.log(result);
});

Passing Query Parameters

Query parameters look like:

/api/products?search=phone&minPrice=100

ASP.NET Core

[HttpGet]
public IActionResult Search(string search, decimal? minPrice)
{
    return Ok(new { search, minPrice });
}

Angular Service

searchProducts(query: string, price: number): Observable<any> {
  return this.http.get(this.apiUrl, {
    params: {
      search: query,
      minPrice: price
    }
  });
}

This is useful for search filters, pagination, and sorting.

Passing Data with PUT (Updating Data)

PUT is used to update existing records.

ASP.NET Core

[HttpPut("{id}")]
public IActionResult UpdateProduct(int id, Product product)
{
    // Update in database
    return Ok(new { Message = "Updated", UpdatedProduct = product });
}

Angular Service

updateProduct(id: number, product: any): Observable<any> {
  return this.http.put(`${this.apiUrl}/${id}`, product);
}

Passing Data with DELETE (Deleting Records)

ASP.NET Core

[HttpDelete("{id}")]
public IActionResult DeleteProduct(int id)
{
    return Ok(new { Message = "Deleted", DeletedId = id });
}

Angular Service

deleteProduct(id: number): Observable<any> {
  return this.http.delete(`${this.apiUrl}/${id}`);
}

Sending Arrays or Lists

Angular can send arrays the same way it sends objects.

Angular

const products = [
  { id: 1, name: "USB Cable", price: 10 },
  { id: 2, name: "Monitor", price: 200 }
];

this.http.post('https://localhost:5001/api/products/bulk', products).subscribe();

ASP.NET Core

[HttpPost("bulk")]
public IActionResult AddBulkProducts(List<Product> products)
{
    return Ok(products);
}

ASP.NET Core automatically binds the list.

Working With JSON (Both Directions)

Both Angular and ASP.NET Core use JSON, so conversion is automatic.

Angular → JSON

Angular converts objects to JSON before sending.

ASP.NET Core → C#

The API converts JSON into your C# classes.

ASP.NET Core → JSON Response

ASP.NET Core automatically serializes C# objects back into JSON.

All conversions are automatic and require no extra code.

Cross-Origin Resource Sharing (CORS)

When Angular runs on a different port from ASP.NET Core, you must enable CORS.

ASP.NET Core Setup

In Program.cs:

builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowAngular",
        policy =>
        {
            policy.WithOrigins("http://localhost:4200")
                  .AllowAnyHeader()
                  .AllowAnyMethod();
        });
});

Enable it:

app.UseCors("AllowAngular");

Without this, Angular requests may fail with a CORS error.

Testing With Postman or Swagger

Before connecting Angular, test the API using:

  • Swagger (built into ASP.NET Core)

  • Postman

Testing ensures your API works correctly before integrating with Angular.

Common Problems and Solutions

1. CORS Error

Fix: Enable CORS in ASP.NET Core.

2. Wrong URL

Fix: Ensure Angular uses the correct endpoint URL.

3. Mismatched Property Names

Angular

productName: 'Laptop'

ASP.NET Core:

public string Name { get; set; }

Fix: Names must match exactly or configure JsonPropertyName.

4. HttpClient Not Injected

Fix: Add HttpClientModule in app.module.ts.

5. Wrong JSON Structure

Angular must send:

{
  "id": 1,
  "name": "Laptop",
  "price": 1200
}

ASP.NET Core model must match.

Summary

Passing data between Angular and ASP.NET Core is simple once you understand the flow:

  1. Angular uses HttpClient to send GET, POST, PUT, DELETE requests.

  2. ASP.NET Core uses controllers to receive and return JSON.

  3. Use route parameters, query parameters, or request bodies based on your needs.

  4. Always enable CORS when Angular and API run on different ports.

  5. Test API before connecting Angular.

Angular and ASP.NET Core work together smoothly, and once you learn the communication pattern, you can build almost any type of web application.