Lecture Topics:
GET
, POST
, PUT
, DELETE
)Lab (4 hours):
ASP.NET Core Web API is a framework for building RESTful services that handle HTTP requests and return JSON/XML data.
Definition:
Web APIs are created using controllers inheriting from ControllerBase
(instead of Controller
used in MVC for views).
Example:
// Controllers/EmployeesController.cs
using Microsoft.AspNetCore.Mvc;
using EmployeeApp.Data;
using EmployeeApp.Models;
using Microsoft.EntityFrameworkCore;
namespace EmployeeApp.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class EmployeesController : ControllerBase
{
private readonly EmployeeContext _context;
public EmployeesController(EmployeeContext context) => _context = context;
[HttpGet]
public async Task<ActionResult<IEnumerable<Employee>>> GetEmployees()
{
return await _context.Employees.ToListAsync();
}
}
}
Key Points:
[ApiController]
for automatic model validation and problem details.[Route("api/[controller]")]
.ActionResult<T>
for flexible HTTP responses (e.g., Ok
, NotFound
).Why This Matters:
Cross-Origin Resource Sharing (CORS) allows a client (e.g., React app) to access the API from a different domain.
Definition:
CORS is configured in Program.cs
to specify allowed origins, methods, and headers.
Example:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowReactApp", builder =>
{
builder.WithOrigins("<http://localhost:3000>") // React app URL
.AllowAnyMethod()
.AllowAnyHeader();
});
});
builder.Services.AddControllers();
builder.Services.AddDbContext<EmployeeContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
var app = builder.Build();
app.UseCors("AllowReactApp");
app.UseRouting();
app.MapControllers();
app.Run();
Key Points:
UseCors
before UseRouting
in middleware pipeline.Why This Matters: