Introduction to ASP.NET Web API

A beginner-to-intermediate course for learning how to build RESTful APIs using ASP.NET Core, C#, controllers, routing, dependency injection, Entity Framework Core, authentication, validation, Swagger, and deployment.

ASP.NET Core C# REST APIs Entity Framework Core Swagger JWT Authentication

Course Overview

This course introduces students to modern API development using ASP.NET Core Web API. Students will learn how to create endpoints, return JSON, connect to databases, protect APIs, test endpoints, and deploy APIs for use by web, mobile, and desktop applications.

Module Topic Suggested Duration
1Introduction to Web APIs2 hrs
2ASP.NET Core Project Structure2 hrs
3Controllers, Actions, and Routing4 hrs
4HTTP Methods and REST Principles3 hrs
5Models, DTOs, and Validation4 hrs
6Dependency Injection and Services3 hrs
7Entity Framework Core Integration5 hrs
8CRUD API Development5 hrs
9Swagger / OpenAPI Documentation2 hrs
10Error Handling and Logging3 hrs
11Authentication and Authorization5 hrs
12API Testing with Postman and Swagger3 hrs
13API Versioning and Best Practices3 hrs
14Deployment to IIS / Cloud4 hrs
15Final Web API Project8 hrs

Total Suggested Duration: 56 Hours

Target Audience

  • Beginners learning backend development with C#
  • ASP.NET MVC developers moving into API development
  • Mobile app developers who need backend services
  • GIS and land information system developers building REST APIs
  • Database developers exposing PostgreSQL, SQL Server, or PostGIS data through APIs

Module 1 — Introduction to Web APIs

Learning Objectives

  • Understand what an API is
  • Understand REST and JSON
  • Know the role of APIs in web and mobile applications
  • Understand client/server communication

Topics

  • What is a Web API?
  • REST architecture
  • JSON responses
  • HTTP request and response lifecycle
  • API consumers: browsers, mobile apps, desktop apps, and services

Module 2 — ASP.NET Core Web API Project Structure

Students learn the structure of a typical ASP.NET Core Web API project.

  • Program.cs
  • Controllers folder
  • Models folder
  • Services folder
  • appsettings.json
  • Middleware pipeline
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();

Module 3 — Controllers, Actions, and Routing

Students learn how API controllers receive requests and return responses.

using Microsoft.AspNetCore.Mvc;

namespace TrainingApi.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class StudentsController : ControllerBase
    {
        [HttpGet]
        public IActionResult GetStudents()
        {
            var students = new[]
            {
                new { Id = 1, Name = "John Doe" },
                new { Id = 2, Name = "Jane Doe" }
            };

            return Ok(students);
        }
    }
}
Practical Exercise: Create a StudentsController and return a list of students as JSON.

Module 4 — HTTP Methods and REST Principles

HTTP Method Purpose Example Route
GETRead data/api/students
GETRead one record/api/students/5
POSTCreate data/api/students
PUTUpdate data/api/students/5
DELETEDelete data/api/students/5
[HttpGet("{id}")]
public IActionResult GetStudent(int id)
{
    return Ok(new { Id = id, Name = "Student " + id });
}

Module 5 — Models, DTOs, and Validation

Students learn how to define data structures and validate incoming API data.

using System.ComponentModel.DataAnnotations;

public class CreateStudentDto
{
    [Required]
    [StringLength(100)]
    public string Name { get; set; } = string.Empty;

    [Required]
    [EmailAddress]
    public string Email { get; set; } = string.Empty;
}
[HttpPost]
public IActionResult CreateStudent(CreateStudentDto model)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    return Created("/api/students/1", model);
}

Module 6 — Dependency Injection and Services

Students learn how to separate business logic from controllers using services.

public interface IStudentService
{
    IEnumerable<string> GetStudentNames();
}

public class StudentService : IStudentService
{
    public IEnumerable<string> GetStudentNames()
    {
        return new List<string> { "John", "Jane", "Mary" };
    }
}
builder.Services.AddScoped<IStudentService, StudentService>();
private readonly IStudentService _studentService;

public StudentsController(IStudentService studentService)
{
    _studentService = studentService;
}

Module 7 — Entity Framework Core Integration

Students learn how to connect an API to a database using Entity Framework Core.

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public string Email { get; set; } = string.Empty;
}
using Microsoft.EntityFrameworkCore;

public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
    {
    }

    public DbSet<Student> Students { get; set; }
}
builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

Module 8 — Building a CRUD API

Students create a complete Create, Read, Update, Delete API.

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

    public StudentsController(AppDbContext context)
    {
        _context = context;
    }

    [HttpGet]
    public IActionResult GetAll()
    {
        return Ok(_context.Students.ToList());
    }

    [HttpPost]
    public IActionResult Create(Student student)
    {
        _context.Students.Add(student);
        _context.SaveChanges();
        return CreatedAtAction(nameof(GetById), new { id = student.Id }, student);
    }

    [HttpGet("{id}")]
    public IActionResult GetById(int id)
    {
        var student = _context.Students.Find(id);
        if (student == null)
            return NotFound();

        return Ok(student);
    }
}

Module 9 — Swagger / OpenAPI Documentation

Students learn how to document and test APIs using Swagger UI.

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

app.UseSwagger();
app.UseSwaggerUI();
Swagger is especially useful when building APIs consumed by mobile apps such as Android, MAUI, or JavaScript frontends.

Module 10 — Error Handling and Logging

  • Using try/catch correctly
  • Returning proper HTTP status codes
  • Global exception handling middleware
  • Logging with ILogger
private readonly ILogger<StudentsController> _logger;

public StudentsController(ILogger<StudentsController> logger)
{
    _logger = logger;
}

[HttpGet("error-test")]
public IActionResult ErrorTest()
{
    _logger.LogInformation("Testing API logging");
    return Ok("Logging works");
}

Module 11 — Authentication and Authorization

Students learn how to protect Web API endpoints using JWT bearer authentication.

[Authorize]
[HttpGet("secure-data")]
public IActionResult GetSecureData()
{
    return Ok(new { Message = "This endpoint requires authentication." });
}

Topics

  • Login endpoint
  • Password verification
  • JWT token generation
  • Bearer token usage
  • Role-based authorization

Module 12 — Testing APIs

Students test API endpoints using Swagger, Postman, browser requests, and command-line tools.

curl -X GET https://localhost:5001/api/students
curl -X POST https://localhost:5001/api/students \
-H "Content-Type: application/json" \
-d "{ \"name\": \"John Doe\", \"email\": \"john@example.com\" }"

Module 13 — API Versioning and Best Practices

  • Use clear route names
  • Use DTOs instead of exposing database entities directly
  • Return correct HTTP status codes
  • Validate all input
  • Use async database calls
  • Secure sensitive endpoints
  • Document all endpoints
[HttpGet]
public async Task<IActionResult> GetAllAsync()
{
    var students = await _context.Students.ToListAsync();
    return Ok(students);
}

Module 14 — Deployment to IIS / Cloud

Students learn how to publish an ASP.NET Core Web API.

Topics

  • Publishing from Visual Studio
  • Publishing using dotnet CLI
  • Hosting on IIS
  • Configuring appsettings.json
  • Connection strings
  • HTTPS certificates
  • Reverse proxy basics
dotnet publish -c Release -o ./publish

Module 15 — Final Project

Students build and present a working Web API project.

Project Option 1 — Student Management API

  • Create students
  • Update students
  • Delete students
  • Search students
  • Document with Swagger

Project Option 2 — Parcel Search API

  • Create parcel records
  • Search parcels by parcel number
  • Return parcel details as JSON
  • Connect to PostgreSQL/PostGIS
  • Expose endpoints for mobile app integration

Project Option 3 — Login and User API

  • User registration
  • Login endpoint
  • JWT authentication
  • Role-based authorization
  • Secure profile endpoint

Recommended Labs

Lab Description
Lab 1Create a new ASP.NET Core Web API project
Lab 2Create your first API controller
Lab 3Build GET, POST, PUT, and DELETE endpoints
Lab 4Add DTOs and validation
Lab 5Connect to a database using Entity Framework Core
Lab 6Document and test APIs with Swagger
Lab 7Add JWT authentication
Lab 8Deploy the API to IIS

Assessment Strategy

Assessment Weight
Weekly Labs30%
CRUD API Assignment20%
Authentication Assignment20%
Final Web API Project30%

Expected Outcomes

By the end of the course, students should be able to:

  • Create ASP.NET Core Web API projects
  • Build RESTful endpoints using controllers
  • Use C# models and DTOs
  • Validate incoming API requests
  • Connect APIs to databases using Entity Framework Core
  • Use dependency injection correctly
  • Document APIs using Swagger
  • Secure APIs using JWT authentication
  • Test APIs with Swagger, Postman, and curl
  • Deploy APIs to IIS or cloud hosting

Recommended Tools

  • Visual Studio 2026
  • .NET SDK
  • SQL Server, PostgreSQL, or SQLite
  • Postman
  • Swagger / OpenAPI
  • Git and GitHub
  • IIS or Azure App Service

Sample API Routes

Route Method Description
/api/studentsGETReturn all students
/api/students/1GETReturn one student
/api/studentsPOSTCreate a student
/api/students/1PUTUpdate a student
/api/students/1DELETEDelete a student
/api/auth/loginPOSTLogin and return JWT token
Suggested Real-World Extension: Connect the final project to a mobile app, MAUI app, or JavaScript frontend so students understand how APIs are consumed in production systems.