NET Centric ComputingUnit 812 min read

React + ASP.NET Core: Integration, Routing, API Calls & Real-World Apps

Unit 8 of NET Centric Computing explores how to combine React.js (a JavaScript library for dynamic UIs) with ASP.NET Core (a backend framework) to build full-stack web applications, covering API communication, routing, state management, and deployment workflows—with Nepalese and global examples like eSewa’s payment UI

Core Concepts: Why React + ASP.NET Core?

1. The Frontend-Backend Split

React (frontend) and ASP.NET Core (backend) are separate but tightly coupled in modern web apps. React handles:

  • User interfaces (buttons, forms, animations)
  • State management (e.g., user login status)
  • Client-side routing (e.g., /products vs /cart)

ASP.NET Core handles:

  • Business logic (e.g., calculating order discounts)
  • Database operations (e.g., fetching user profiles)
  • Authentication (e.g., JWT tokens for secure APIs)

Why combine them?

  • Separation of concerns: Frontend teams (React devs) and backend teams (C# devs) work independently.
  • Scalability: React can be reused across projects; ASP.NET Core APIs can serve mobile apps too.
  • Performance: React renders only what’s needed (virtual DOM), while ASP.NET Core processes requests efficiently.

2. How They Communicate: HTTP and APIs

React and ASP.NET Core talk via HTTP requests (GET, POST, PUT, DELETE). ASP.NET Core exposes RESTful APIs (endpoints like /api/products), and React calls them using:

  • Fetch API (built into browsers)
  • Axios (a popular library for cleaner code)
Request InitiationReact sends `GET/api/products` to ASP.Server ProcessingASP.NET Corequeries SQL Server (T-ResponseJSON payloadreturned (e.g., `{"id"UI UpdateReact rendersproduct card (React 18
HTTP request lifecycle in a Daraz-like app (latency: ~150ms)

Example: Fetching Products from Daraz

Suppose Daraz’s backend (ASP.NET Core) has this API endpoint:

GET /api/products?category=electronics

React would call it like this (using Axios):

axios.get('/api/products?category=electronics')
  .then(response => {
    // Update React state with the product list
    setProducts(response.data);
  });

Visual: API Call Flow

sequenceDiagram
    participant User as React Frontend (Browser)
    participant API as ASP.NET Core API
    participant DB as Database (SQL Server)

    User->>API: GET /api/products (HTTP Request)
    API->>DB: SELECT * FROM Products WHERE category='electronics'
    DB-->>API: Returns product data
    API-->>User: JSON response (e.g., [{id:1, name:"Laptop"}, ...])
    User->>User: Renders product cards in UI

3. Key Integration Techniques

classDiagram
    class ReactFrontend {
        +useState()
        +useEffect()
        +axios.get()
    }
    class ASPNETCoreAPI {
        +[HttpGet] GetPayments()
        +[HttpPost] AddPayment()
    }
    class SQLServer {
        +Payments Table
    }
    ReactFrontend --> ASPNETCoreAPI : Calls via HTTP
    ASPNETCoreAPI --> SQLServer : CRUD Operations
Class diagram of the payment tracker app’s data flow

A. Proxy Setup in ASP.NET Core

To avoid CORS (Cross-Origin Resource Sharing) errors, configure ASP.NET Core to allow requests from your React app’s origin:

// Program.cs in ASP.NET Core
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowReactApp",
        builder => builder.WithOrigins("http://localhost:3000") // React's default port
                         .AllowAnyMethod()
                         .AllowAnyHeader());
});

Real-World Tie-In: eSewa’s web app uses a similar setup. When you log in via React, the frontend sends credentials to the ASP.NET Core backend (hosted on NTC’s servers), which validates them against the database.


B. Routing: Client-Side vs. Server-Side

Feature React Router (Client-Side) ASP.NET Core (Server-Side)
How it works Changes URL without page reload Requires full server request
Example /products/123 → Shows Product 123 /Home/Index/123 → Renders view
Use Case Single-Page Apps (SPAs) Traditional multi-page apps
Performance Faster (no round-trip to server) Slower (full HTML response)

Example: React Router Setup

// In your React app (e.g., App.js)
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';

function App() {
  return (
    <Router>
      <Routes>
        <Route path="/products" element={<ProductList />} />
        <Route path="/products/:id" element={<ProductDetail />} />
      </Routes>
    </Router>
  );
}

Visual: Routing in a Daraz-Like App

graph TD
    A["Homepage"] -->|"Click 'Electronics'"| B[/products?category=electronics]
    B --> C["React fetches data from ASP.NET Core API"]
    C --> D["Displays product grid"]
    D -->|"Click 'Laptop'"| E[/products/123]
    E --> F["React shows laptop details"]

C. State Management: Where Does Data Live?

Scenario Where Data is Stored Example
Temporary UI state React (useState, useReducer) Cart items before checkout
Shared across pages ASP.NET Core (Session/Redis) User login status
Persistent data Database (SQL Server) Product inventory

Worked Example: Kathmandu Traffic Routes (Analogy) Imagine Kathmandu’s traffic lights:

  • React state = Temporary signals (e.g., "Turn left at next light").
  • ASP.NET Core session = Permanent rules (e.g., "No right turns on Thapathali").
  • Database = Road maps (e.g., "Route 100 connects Patan to Nagarjuna").

4. Building a Full-Stack App: Step-by-Step

Let’s build a simple eSewa-like payment tracker using React + ASP.NET Core.

Step 1: ASP.NET Core API (Backend)

Create a controller to track payments:

[ApiController]
[Route("api/[controller]")]
public class PaymentsController : ControllerBase
{
    private static List<Payment> _payments = new();

    [HttpGet]
    public IActionResult GetPayments()
    {
        return Ok(_payments);
    }

    [HttpPost]
    public IActionResult AddPayment([FromBody] Payment payment)
    {
        _payments.Add(payment);
        return CreatedAtAction(nameof(GetPayments), payment);
    }
}

public class Payment
{
    public string TransactionId { get; set; }
    public decimal Amount { get; set; }
    public string Status { get; set; } // "Pending", "Completed"
}

Step 2: React Frontend (Payment Tracker UI)

// PaymentList.js
import React, { useState, useEffect } from 'react';
import axios from 'axios';

function PaymentList() {
  const [payments, setPayments] = useState([]);

  useEffect(() => {
    axios.get('/api/payments')
      .then(response => setPayments(response.data));
  }, []);

  const addPayment = () => {
    axios.post('/api/payments', {
      transactionId: "TXN123",
      amount: 500,
      status: "Pending"
    });
  };

  return (
    <div>
      <button onClick={addPayment}>Add Payment</button>
      <ul>
        {payments.map(p => (
          <li key={p.transactionId}>
            {p.amount} NPR - {p.status}
          </li>
        ))}
      </ul>
    </div>
  );
}

Visual: Payment Flow in eSewa



5. Deployment Workflow

  1. React App: Build with npm run build → Outputs static files (/build).
  2. ASP.NET Core: Hosts the API (e.g., on Azure or a Nepalese VPS).
  3. Serve Static Files: Configure ASP.NET Core to serve React’s build folder:
    app.UseStaticFiles(); // Serves React's index.html and JS files
    app.UseSpaStaticFiles(); // For SPA routing
    

Real-World Example:

  • Pathao’s Rider App: React frontend (for rider UI) + ASP.NET Core backend (for order processing).
  • NEPSE’s Stock Tracker: React dashboards (client-side) + ASP.NET Core APIs (server-side data).

6. Advantages and Challenges

Advantages Challenges
✅ Modularity: Teams can work in parallel ❌ Complexity: Requires knowledge of both React and C#
✅ Reusability: React components can be shared across projects ❌ Debugging: Harder to trace issues across frontend/backend
✅ Performance: Fast client-side rendering ❌ Security: CORS, XSS, and CSRF risks if not configured properly
✅ Scalability: ASP.NET Core handles high traffic (e.g., Daraz during sales) ❌ Initial Setup: Requires proxy, routing, and state management configuration

In the Real World

  1. eSewa (Nepal)

    • What it uses: React for the mobile/web UI (e.g., payment confirmation screens) + ASP.NET Core for transaction processing and bank integrations.
    • How it works: When you pay a bill, React sends the transaction details to the ASP.NET Core backend, which debits your account and credits the service provider (e.g., NTC).
  2. Daraz (Global)

    • What it uses: React for the product catalog and cart (client-side) + ASP.NET Core for inventory management and order routing.
    • How it works: When you add items to your cart, React updates the UI instantly (no page reload). The backend (ASP.NET Core) only processes the order when you click "Checkout."
  3. Ncell’s MyNcell App

    • What it uses: React for the recharge and data bundle UI + ASP.NET Core for SIM authentication and balance checks.
    • How it works: The app’s "Check Balance" button triggers a React state update, which calls the ASP.NET Core API to fetch your remaining talk time/data.

Exam Tip

What to Expect in TU/PU Exams

  1. Short Questions (2–5 marks):

    • Define CORS, REST API, or virtual DOM.
    • Compare React Router with ASP.NET Core routing.
    • Write a single API call in React (e.g., fetch or axios).
  2. Long Questions (10–15 marks):

    • Design a full-stack app: Sketch the flow (e.g., "Build a Pathao rider app with React + ASP.NET Core").
    • Code snippets: Given a React component, write the corresponding ASP.NET Core controller (or vice versa).
    • State management: Explain where to store data (React state vs. backend session) with an example.
  3. Practical (Programming) Questions:

    • Implement a CRUD API in ASP.NET Core and show how React would consume it.
    • Debug a CORS error or 404 route mismatch.

How to Score Full Marks

  • Diagrams: Always draw a sequence diagram for API calls (like the Daraz example above).
  • Code: Use realistic examples (e.g., eSewa payments, Daraz products).
  • Explanations: Link concepts to Nepalese apps (e.g., "Like how eSewa’s UI updates without refreshing...").
  • Error Handling: Mention CORS, authentication, and error boundaries in React.

Key Formulas/Checklists

Topic Exam-Friendly Summary
API Endpoint GET /api/[controller] → Returns data; POST /api/[controller] → Creates data.
React State useState for temporary data; useEffect to fetch from ASP.NET Core.
CORS Setup builder.WithOrigins("http://localhost:3000") in ASP.NET Core.
Routing React: <Route path="/products" />; ASP.NET Core: [Route("api/products")].

Common Pitfalls

  • ❌ Ignoring CORS: Forgetting to configure AddCors in ASP.NET Core will break React API calls.
  • ❌ Hardcoding API URLs: Use environment variables (e.g., process.env.REACT_APP_API_URL).
  • ❌ Not handling errors: Always add .catch(error => console.error(error)) in React API calls.
  • ❌ Mixing frontend/backend logic: Keep business rules (e.g., discount calculations) in ASP.NET Core, not React.

In the real world

  • eSewa: Uses React frontend (for transaction UI) + ASP.NET Core backend (for payment validation) with JWT authentication (stored in ASP.NET Core’s session).
  • Daraz: Employs client-side routing (React Router) for /products pages while server-side routing (ASP.NET Core) handles /checkout (requires full-page reload for security).
  • Ncell’s MyNcell App: Combines React state (for temporary cart items) with ASP.NET Core’s Redis cache (for shared user sessions across devices).

Based on the TU BIT syllabus for NET Centric Computing (BIT351), unit 8.

Discussion

Loading…