⚛ React + ASP.NET Core Guide

5. Call the API from React

A small end-to-end example: an ASP.NET Core to-do API and a React component that uses it.

1. Add an API endpoint (server)

Add to Program.cs before app.Run(). This uses minimal APIs and an in-memory list for simplicity:

var todos = new List<TodoItem>
{
    new(1, "Create the project", true),
    new(2, "Call the API from React", false)
};

app.MapGet("/api/todos", () => todos);

app.MapPost("/api/todos", (NewTodo input) =>
{
    var item = new TodoItem(todos.Max(t => t.Id) + 1, input.Title, false);
    todos.Add(item);
    return Results.Created($"/api/todos/{item.Id}", item);
});

app.MapFallbackToFile("/index.html");
app.Run();

record TodoItem(int Id, string Title, bool Done);
record NewTodo(string Title);

Remember to keep types such as the records after the top-level statements, and keep MapFallbackToFile after your API routes.

2. Make sure the proxy covers /api

In vite.config.js, the '^/api' pattern from the previous step forwards every /api/... request to the server.

3. Build the React component (client)

Create src/Todos.jsx:

import { useEffect, useState } from 'react';

export default function Todos() {
  const [todos, setTodos] = useState([]);
  const [title, setTitle] = useState('');
  const [error, setError] = useState(null);

  useEffect(() => {
    fetch('/api/todos')
      .then(response => {
        if (!response.ok) throw new Error('Request failed: ' + response.status);
        return response.json();
      })
      .then(setTodos)
      .catch(err => setError(err.message));
  }, []);

  async function addTodo(e) {
    e.preventDefault();
    if (!title.trim()) return;

    const response = await fetch('/api/todos', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ title })
    });
    if (response.ok) {
      const created = await response.json();
      setTodos(current => [...current, created]);
      setTitle('');
    }
  }

  if (error) return <p role="alert">Could not load to-dos: {error}</p>;

  return (
    <section>
      <h2>To-dos</h2>
      <ul>
        {todos.map(t => (
          <li key={t.id}>{t.done ? '✔ ' : ''}{t.title}</li>
        ))}
      </ul>
      <form onSubmit={addTodo}>
        <input value={title} onChange={e => setTitle(e.target.value)} placeholder="New to-do" />
        <button type="submit">Add</button>
      </form>
    </section>
  );
}

4. Use it in App.jsx

import Todos from './Todos';

export default function App() {
  return (
    <main>
      <h1>My React + ASP.NET Core app</h1>
      <Todos />
    </main>
  );
}

Use relative URLs

Always call /api/... with a relative URL. In development the Vite proxy handles it; in production the same origin serves both files and API, so nothing changes.

CORS: you don't need it with the proxy approach. Only enable CORS in ASP.NET Core if the React app is hosted on a different origin than the API.