Lecture Topics:
Lab:
This section introduces combining ASP.NET MVC Core (backend) with React (frontend) to build a full-stack application.
Employee
data.This involves creating an ASP.NET MVC Core project with a React frontend.
Steps:
Create MVC Project with React:
In Visual Studio 2022, select “ASP.NET Core with React.js” template:
dotnet new react -o EmployeeApp
This creates:
ClientApp
folder.SpaServices
for development.Project Structure:
Controllers/
: API controllers (e.g., EmployeesController
).ClientApp/
: React app (contains src/
, package.json
).appsettings.json
: Configuration (e.g., database connection).Program.cs
: Configures services and middleware.Install Dependencies:
Backend (EF Core for database, Newtonsoft.Json for serialization):
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet add package Newtonsoft.Json
Frontend (React dependencies, e.g., axios
):
cd ClientApp
npm install axios
Configure Development:
The template uses SpaProxy
to proxy React (http://localhost:3000
) to the MVC backend (http://localhost:5000
).
Update Program.cs
for CORS and services:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowReactApp", builder =>
{
builder.WithOrigins("<http://localhost:3000>")
.AllowAnyMethod()
.AllowAnyHeader();
});
});
builder.Services.AddControllers().AddNewtonsoftJson();
builder.Services.AddDbContext<EmployeeContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddSpaStaticFiles(configuration =>
configuration.RootPath = "ClientApp/build");
var app = builder.Build();
app.UseCors("AllowReactApp");
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (app.Environment.IsDevelopment())
{
spa.UseReactDevelopmentServer(npmScript: "start");
}
});
app.UseRouting();
app.MapControllers();
app.Run();
Key Points:
ClientApp
is a standard React project using create-react-app
.npm start
in ClientApp
for frontend development.Why This Matters: