How does a .NET Full Stack Developer manage communication between the frontend (like Angular or React) and the backend (ASP.NET Core) using RESTful APIs?

How Does a .NET Full Stack Developer Manage Communication Between Frontend and Backend Using RESTful APIs?

In full stack development using .NET, seamless communication between the frontend and backend is essential for building dynamic, data-driven web applications. This communication is typically handled through RESTful APIs, where the backend (ASP.NET Core) exposes endpoints, and the frontend (React or Angular) consumes them.


Let’s break down the process step by step:

๐Ÿ”ง Backend Setup with ASP.NET Core

1. Define a Model (Data Structure)

public class Employee

{

    public int Id { get; set; }

    public string Name { get; set; }

    public string Department { get; set; }

}

2. Create a Data Access Layer or Service

public interface IEmployeeService

{

    List<Employee> GetAll();

    Employee GetById(int id);

    void Add(Employee employee);

}


public class EmployeeService : IEmployeeService

{

    private static List<Employee> _employees = new List<Employee>();


    public List<Employee> GetAll() => _employees;


    public Employee GetById(int id) => _employees.FirstOrDefault(e => e.Id == id);


    public void Add(Employee employee) => _employees.Add(employee);

}

3. Register Service in Dependency Injection

public void ConfigureServices(IServiceCollection services)

{

    services.AddControllers();

    services.AddSingleton<IEmployeeService, EmployeeService>();

    services.AddCors(options =>

    {

        options.AddPolicy("AllowAll", builder =>

            builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());

    });

}

4. Create an API Controller

[ApiController]

[Route("api/[controller]")]

public class EmployeesController : ControllerBase

{

    private readonly IEmployeeService _employeeService;


    public EmployeesController(IEmployeeService employeeService)

    {

        _employeeService = employeeService;

    }


    [HttpGet]

    public IActionResult GetAll() => Ok(_employeeService.GetAll());


    [HttpGet("{id}")]

    public IActionResult GetById(int id)

    {

        var emp = _employeeService.GetById(id);

        if (emp == null) return NotFound();

        return Ok(emp);

    }


    [HttpPost]

    public IActionResult Add([FromBody] Employee employee)

    {

        _employeeService.Add(employee);

        return CreatedAtAction(nameof(GetById), new { id = employee.Id }, employee);

    }

}

5. Enable CORS in Middleware

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

{

    app.UseCors("AllowAll");

    app.UseRouting();

    app.UseEndpoints(endpoints =>

    {

        endpoints.MapControllers();

    });

}

๐ŸŒ Frontend (React Example)

1. Install Axios

npm install axios

2. Create API Service (api.js)

import axios from 'axios';

const BASE_URL = "https://localhost:5001/api/employees";

export const getAllEmployees = () => axios.get(BASE_URL);

export const getEmployeeById = (id) => axios.get(`${BASE_URL}/${id}`);

export const addEmployee = (employee) => axios.post(BASE_URL, employee);

3. Use API in React Component

import React, { useEffect, useState } from 'react';

import { getAllEmployees, addEmployee } from './api';


function EmployeeList() {

    const [employees, setEmployees] = useState([]);

    const [name, setName] = useState('');

    const [department, setDepartment] = useState('');


    useEffect(() => {

        loadEmployees();

    }, []);


    const loadEmployees = async () => {

        const response = await getAllEmployees();

        setEmployees(response.data);

    };


    const handleSubmit = async (e) => {

        e.preventDefault();

        const newEmployee = { id: Date.now(), name, department };

        await addEmployee(newEmployee);

        loadEmployees();

        setName('');

        setDepartment('');

    };


    return (

        <div>

            <h2>Employee List</h2>

            <form onSubmit={handleSubmit}>

                <input value={name} onChange={(e) => setName(e.target.value)} placeholder="Name" />

                <input value={department} onChange={(e) => setDepartment(e.target.value)} placeholder="Department" />

                <button type="submit">Add</button>

            </form>

            <ul>

                {employees.map(emp => (

                    <li key={emp.id}>{emp.name} - {emp.department}</li>

                ))}

            </ul>

        </div>

    );

}


⚙️ Key Concepts

1. RESTful API

Follows standard HTTP methods: GET, POST, PUT, DELETE

Stateless communication

Clean and consistent endpoint naming (/api/employees)

2. CORS (Cross-Origin Resource Sharing)

Browsers block requests from one origin to another by default

CORS must be enabled in ASP.NET Core to allow frontend access

3. Axios or Fetch

Used to call APIs from frontend

Supports promises and error handling


๐Ÿ” Data Flow Summary

User fills a form in React.

React sends POST request to ASP.NET Core API.

API controller receives data and updates the list.

React re-fetches the employee list via GET request.

UI updates with the latest data.

๐Ÿ” Bonus: Secure Communication

Use HTTPS (SSL/TLS)

Implement authentication (e.g., JWT tokens)

Validate incoming data in controllers


✅ Best Practices

Separate API and business logic using services

Handle errors gracefully on both frontend and backend

Use interfaces for DI in .NET

Organize frontend code into reusable components

Write unit tests for APIs and UI components

๐ŸŽฏ Conclusion

A .NET Full Stack Developer bridges the frontend and backend using RESTful APIs. With ASP.NET Core providing powerful backend support and React or Angular handling interactive frontends, REST APIs ensure smooth, scalable, and efficient communication. Proper CORS setup, HTTP methods, and structured data exchange play a crucial role in building reliable full stack applications.

Comments

Popular posts from this blog

What is WebDriver in Selenium? Explained with Java

Tosca System Requirements and Installation Guide (Step-by-Step)

Why Choose Python for Full-Stack Web Development