ASP.NET Core Web API Step-by-Step Tutorial (2026)

Introduction

ASP.NET Core Web API is the backbone of modern .NET applications. It is used to build RESTful services that power:

  • Web applications
  • Mobile apps
  • Angular / React frontends
  • Microservices
  • Cloud-native systems

Many developers can create a Web API, but struggle with:

  • Project structure
  • Dependency injection
  • Validation
  • Exception handling
  • Real-world best practices

This tutorial explains ASP.NET Core Web API from scratch, with clean architecture, real CRUD examples, and production-ready patterns.


What Is ASP.NET Core Web API?

ASP.NET Core Web API is a framework for building HTTP-based APIs using C# and .NET.

It supports:

  • REST principles
  • JSON by default
  • Dependency Injection
  • Middleware pipeline
  • High performance & cross-platform execution

Why Web API?

  • ✔ Decouples frontend and backend
  • ✔ Works with any client (Web / Mobile)
  • ✔ Scales well in cloud environments

REST Basics (Very Important)

A REST API uses HTTP verbs to perform actions:

HTTP Verb Purpose
GET Read data
POST Create data
PUT Update data
DELETE Remove data

Each resource is identified using a URL.


GET /api/employees

Creating an ASP.NET Core Web API Project


dotnet new webapi -n EmployeeApi
cd EmployeeApi
dotnet run

Project Structure


EmployeeApi
│── Controllers
│── Models
│── Program.cs
│── appsettings.json

Program.cs Explained (Minimal Hosting Model)


var builder = WebApplication.CreateBuilder(args);

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

var app = builder.Build();

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

app.Run();
  • ✔ Services configured first
  • ✔ Middleware pipeline executed in order

Controllers & Routing

API Controller Example


[ApiController]
[Route("api/[controller]")]
public class EmployeesController : ControllerBase
{
    [HttpGet]
    public IActionResult Get()
    {
        return Ok("Employee list");
    }
}

Attribute Routing


[HttpGet("{id}")]
public IActionResult GetById(int id)
  • ✔ Clear
  • ✔ Explicit
  • ✔ Preferred over conventional routing

Models (DTOs vs Entities)

Entity Model


public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Salary { get; set; }
}

DTO (Recommended)


public class EmployeeDto
{
    public string Name { get; set; }
    public decimal Salary { get; set; }
}
  • ✔ Prevents over-posting
  • ✔ Cleaner API contracts

Dependency Injection (Core Strength)

ASP.NET Core has built-in DI.

Service Interface


public interface IEmployeeService
{
    IEnumerable<Employee> GetAll();
}

Service Implementation


public class EmployeeService : IEmployeeService
{
    public IEnumerable<Employee> GetAll()
    {
        return new List<Employee>();
    }
}

Register Service


builder.Services.AddScoped<IEmployeeService, EmployeeService>();

Inject into Controller


public EmployeesController(IEmployeeService service)
{
    _service = service;
}

CRUD Operations (Real Example)

GET – Read


[HttpGet]
public IActionResult GetAll()
{
    return Ok(_service.GetAll());
}

POST – Create


[HttpPost]
public IActionResult Create(EmployeeDto dto)
{
    return CreatedAtAction(nameof(GetAll), dto);
}

PUT – Update


[HttpPut("{id}")]
public IActionResult Update(int id, EmployeeDto dto)
{
    return NoContent();
}

DELETE – Remove


[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
    return NoContent();
}

Model Validation

Data Annotations


public class EmployeeDto
{
    [Required]
    public string Name { get; set; }

    [Range(10000, 100000)]
    public decimal Salary { get; set; }
}

ASP.NET Core automatically returns 400 Bad Request if validation fails.

  • ✔ Clean
  • ✔ No extra code

Exception Handling (Production Ready)

Global Exception Middleware


app.UseExceptionHandler(appError =>
{
    appError.Run(async context =>
    {
        context.Response.StatusCode = 500;
        await context.Response.WriteAsync("Something went wrong");
    });
});
  • ✔ Centralized
  • ✔ Cleaner controllers

Logging Best Practices


private readonly ILogger<EmployeesController> _logger;

_logger.LogInformation("Fetching employees");
  • ✔ Built-in logging
  • ✔ Works with Serilog / App Insights

Swagger (API Documentation)

Swagger is enabled by default.


https://localhost:5001/swagger
  • ✔ Auto-generated docs
  • ✔ Test APIs easily
  • ✔ Required for real projects

HTTP Status Codes (Correct Usage)

Code Meaning
200 OK
201 Created
204 No Content
400 Bad Request
404 Not Found
500 Server Error

Correct status codes = Professional API.


Web API Best Practices

  • ✔ Use DTOs
  • ✔ Keep controllers thin
  • ✔ Business logic in services
  • ✔ Validate input
  • ✔ Handle errors globally
  • ✔ Version APIs (/api/v1/)

Common Mistakes

  • Writing business logic in controllers
  • Returning entities directly
  • Ignoring status codes
  • No validation
  • No error handling

Web API Interview Questions (Quick)

Q: What is middleware?
A: A component that handles requests/responses in pipeline.

Q: Difference between PUT and POST?
A: POST creates, PUT updates.

Q: What is dependency injection?
A: Injecting dependencies instead of creating them manually.


Summary

ASP.NET Core Web API:

  • Is fast and scalable
  • Supports clean architecture
  • Is ideal for modern backend development

Mastering Web API means understanding:

  • ✔ Routing
  • ✔ Dependency Injection
  • ✔ Validation
  • ✔ Error handling
  • ✔ REST principles

FAQ

Is ASP.NET Core Web API suitable for microservices?
Yes.

Can it be used with Angular / React?
Absolutely.

Is Web API better than MVC for APIs?
Yes — Web API is designed for APIs.

Comments

Popular posts from this blog

Debouncing & Throttling in RxJS: Optimizing API Calls and User Interactions

Promises in Angular

Comprehensive Guide to C# and .NET Core OOP Concepts and Language Features