Connecting a React frontend with an ASP.NET Core Web API is one of the most common architectures used in modern web applications. This setup follows a decoupled client-server model where React handles the user interface and ASP.NET Core manages business logic, authentication, and data access. Understanding how these two layers communicate is essential for building scalable, secure, and maintainable full-stack applications.
This article provides a complete, real-world explanation of how to connect React with ASP.NET Core Web API, including architecture flow, CORS configuration, API consumption, authentication basics, common mistakes, and production best practices.
What Does It Mean to Connect React With ASP.NET Core Web API?
In simple terms, React sends HTTP requests (GET, POST, PUT, DELETE) to ASP.NET Core endpoints, and the API returns JSON responses. React then renders that data in the browser.
Technically, this communication happens over HTTP/HTTPS using RESTful APIs. The frontend and backend can run on different ports or even different servers in production.
Why This Architecture Is Popular
This separation of concerns provides several benefits:
In enterprise systems, this pattern enables microservices and cloud-native deployments.
Real-World Analogy
Think of React as a restaurant customer and ASP.NET Core Web API as the kitchen.
The customer (React) places an order (HTTP request).
The kitchen (API) prepares the food (processes business logic).
The waiter returns the dish (JSON response).
The customer never enters the kitchen. Communication happens through a defined interface.
Architecture Flow Explanation
User → React UI → Axios/Fetch → ASP.NET Core Controller → Service Layer → Database → Response → React UI Update
This clear request-response cycle ensures loose coupling between frontend and backend.
Step 1: Create ASP.NET Core Web API
Create a simple controller:
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
var products = new[]
{
new { Id = 1, Name = "Laptop", Price = 80000 },
new { Id = 2, Name = "Mobile", Price = 30000 }
};
return Ok(products);
}
}
Run the API. It may run on:
https://localhost:5001
Step 2: Enable CORS in ASP.NET Core
Since React runs on a different port (e.g., http://localhost:3000), you must enable CORS (Cross-Origin Resource Sharing).
In Program.cs:
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowReactApp",
policy =>
{
policy.WithOrigins("http://localhost:3000")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
app.UseCors("AllowReactApp");
Without CORS configuration, the browser will block requests for security reasons.
Step 3: Create React Application
Create a React app:
npx create-react-app clientapp
cd clientapp
npm start
Install Axios (recommended HTTP client):
npm install axios
Step 4: Call ASP.NET Core API From React
Inside a React component:
import React, { useEffect, useState } from "react";
import axios from "axios";
function Products() {
const [products, setProducts] = useState([]);
useEffect(() => {
axios.get("https://localhost:5001/api/products")
.then(response => {
setProducts(response.data);
})
.catch(error => {
console.error("Error fetching data:", error);
});
}, []);
return (
<div>
<h2>Product List</h2>
<ul>
{products.map(product => (
<li key={product.id}>
{product.name} - ₹{product.price}
</li>
))}
</ul>
</div>
);
}
export default Products;
Now React fetches data from the ASP.NET Core Web API and displays it dynamically.
Real Business Scenario: E-Commerce Application
In an e-commerce system:
React displays product catalog.
ASP.NET Core handles order processing.
Authentication is managed via JWT tokens.
Payment processing happens via secure backend endpoints.
The frontend never directly connects to the database; it always communicates through the API layer.
Adding Authentication (Basic Overview)
In production applications, APIs are secured using JWT authentication.
Flow:
User logs in from React.
API validates credentials.
API returns JWT token.
React stores token (preferably in memory or secure storage).
React sends token in Authorization header.
Example header:
axios.get("https://localhost:5001/api/products", {
headers: {
Authorization: `Bearer ${token}`
}
});
Advantages of This Architecture
Clean separation of frontend and backend
Independent scaling
Better security
API reusable for mobile applications
Microservices compatibility
Disadvantages
Requires proper CORS configuration
Slightly more complex setup
Authentication handling complexity
Network latency between frontend and backend
Common Mistakes Developers Make
Forgetting to enable CORS
Hardcoding API URLs instead of using environment variables
Not handling API errors properly
Exposing sensitive data in API responses
Not using HTTPS in production
Best Practices for Production
Use environment variables for API base URL
Enable HTTPS always
Use JWT authentication
Implement proper error handling middleware
Use API versioning
Implement logging and monitoring
Apply rate limiting and validation
When NOT to Use This Approach
If you are building a small internal application with minimal complexity, using server-side rendering with Razor Pages may be simpler. However, for scalable, modern web applications, React with ASP.NET Core Web API is a preferred approach.
FAQ
Can React and ASP.NET Core run on the same server?
Yes. In production, React can be built and served as static files from ASP.NET Core.
Should we use Fetch or Axios?
Both work. Axios provides better error handling and interceptors.
Can we deploy them separately?
Yes. React can be hosted on static hosting (e.g., Azure Static Web Apps) and API on Azure App Service.
Conclusion
Connecting React frontend with ASP.NET Core Web API enables a powerful, scalable, and maintainable full-stack architecture built on a clear separation of concerns. By properly configuring CORS, handling authentication securely, structuring API endpoints cleanly, and following production best practices such as HTTPS enforcement and environment-based configuration, developers can build enterprise-grade applications that scale efficiently and support web, mobile, and distributed systems seamlessly.