How to Build a Full-Stack Web App Using ASP.NET and React

ASP.NET and React are a powerful combination for building modern, scalable, and high-performance full-stack web applications. In this guide, we’ll walk through the step-by-step process of developing a full-stack web app using ASP.NET Core for the backend and React for the frontend.


Why Choose ASP.NET and React?

Scalability: ASP.NET handles high-performance server-side operations, while React ensures a dynamic frontend.
Separation of Concerns: Clear distinction between backend (API) and frontend (UI).
Security & Performance: ASP.NET Core provides built-in security features, and React ensures fast rendering with Virtual DOM.
Cross-Platform Development: Develop and deploy apps on Windows, macOS, and Linux.


1. Setting Up the Development Environment

Install Required Tools

  • Visual Studio 2022 (for ASP.NET development) or VS Code
  • .NET SDK (latest version)
  • Node.js (LTS version)
  • Postman or Swagger (for API testing)

Create an ASP.NET Core Web API Project

  1. Open Visual Studio and select Create a new project.
  2. Choose ASP.NET Core Web API and click Next.
  3. Configure the project name and click Create.
  4. Select .NET 7+ and click Create.
  5. Run the default project to verify it works using dotnet run.

2. Setting Up the Backend (ASP.NET Core API)

Create a Model and Database Context

In the Models folder, create a class for your data structure. Example:

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

Now, create a Database Context in Data/ApplicationDbContext.cs:

using Microsoft.EntityFrameworkCore;
public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) {}
    public DbSet<Product> Products { get; set; }
}

Add Entity Framework and Migrate the Database

Run these commands in the terminal:

dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
dotnet ef migrations add InitialCreate
dotnet ef database update

3. Creating the API Endpoints

In Controllers/ProductController.cs, create a simple API to manage products:

[Route("api/[controller]")]
[ApiController]
public class ProductController : ControllerBase
{
    private readonly ApplicationDbContext _context;

    public ProductController(ApplicationDbContext context)
    {
        _context = context;
    }

    [HttpGet]
    public async Task<ActionResult<IEnumerable<Product>>> GetProducts()
    {
        return await _context.Products.ToListAsync();
    }
}

Test the API using Postman or Swagger (/swagger endpoint).


4. Setting Up the Frontend (React)

Create a React App

Run the following command:

npx create-react-app myapp --template typescript
cd myapp
npm install axios react-router-dom

Fetching Data from ASP.NET API

Edit src/App.tsx to fetch and display data:

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

interface Product {
  id: number;
  name: string;
  price: number;
}

const App: React.FC = () => {
  const [products, setProducts] = useState<Product[]>([]);

  useEffect(() => {
    axios.get('https://localhost:5001/api/product')
      .then(response => setProducts(response.data))
      .catch(error => console.error(error));
  }, []);

  return (
    <div>
      <h1>Product List</h1>
      <ul>
        {products.map(product => (
          <li key={product.id}>{product.name} - ${product.price}</li>
        ))}
      </ul>
    </div>
  );
};

export default App;

Run the React App

npm start

Now, React should successfully fetch data from your ASP.NET API!


5. Connecting the Frontend & Backend

Enable CORS in ASP.NET Core

Add the following in Program.cs:

builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowAll",
        policy => policy.AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowAnyHeader());
});
app.UseCors("AllowAll");

Update Axios to Use Correct API URL

In App.tsx, update the API endpoint:

axios.get('http://localhost:5001/api/product')

6. Deploying the Application

Deploy the Backend to Azure or AWS

  • Use Azure App Service or AWS Elastic Beanstalk to deploy the ASP.NET Core API.

Deploy the Frontend

  • Use Vercel, Netlify, or AWS S3 to deploy the React frontend.

Final Step: Update API Endpoint in Production

Modify the React API URL to point to the hosted backend.


Conclusion

By following this guide, you’ve built a fully functional full-stack web app using ASP.NET Core and React. You’ve learned: ✅ How to set up a backend with ASP.NET Core ✅ How to build a frontend with React ✅ How to connect both using API calls ✅ How to deploy your application

Next Steps: Add authentication using JWT or OAuth, integrate a database like SQL Server or PostgreSQL, and improve the UI with Material-UI or Tailwind CSS!

Start building and take your full-stack development skills to the next level!

Leave a Reply

Your email address will not be published. Required fields are marked *