Lesson 32 of 40 Web API Intermediate 40 min

Routing in Web API

Learn how routing works in ASP.NET Core Web API and how to define clean, flexible, and meaningful API endpoints. Routing determines how HTTP requests are mapped to controller actions.

Part 1: What Is Routing?

Routing is the process of matching an incoming HTTP request URL to a specific controller action. It tells the application which code should handle the request.

In Web API, routing is essential because APIs rely entirely on URLs and HTTP methods.

Part 2: Attribute Routing

ASP.NET Core Web API uses attribute routing, where routes are defined using attributes directly on controllers and actions.

[ApiController]
[Route("api/[controller]")]
public class StudentApiController : ControllerBase

This sets the base route to /api/studentapi.

Part 3: Defining Routes for Actions

Each action method can define its own route using HTTP method attributes.

[HttpGet]
public IEnumerable<string> GetAll()
{
  return new string[] { "Alice", "Bob" };
}

[HttpGet("{id}")]
public string GetById(int id)
{
  return "Student " + id;
}

These routes allow:

Part 4: Route Parameters

Route parameters allow dynamic values to be passed through the URL.

[HttpGet("{id}")]

The {id} placeholder is replaced with actual values in the request.

Part 5: Combining Routes and HTTP Methods

Web API routes are often combined with HTTP methods to define clear operations.

HTTP Method Route Purpose
GET /api/students Retrieve all students
GET /api/students/1 Retrieve a specific student
POST /api/students Create a new student
PUT /api/students/1 Update a student
DELETE /api/students/1 Delete a student

Part 6: Route Naming Best Practices

Good API design uses clear and consistent naming conventions.

This makes your API easier to understand and maintain.

Part 7: Routing in the Student Project

In your Student CRUD API, routing allows you to expose data endpoints:

Proper routing design makes your API professional and easy to use.

Part 8: Best Practices

Good routing design is the foundation of a well-structured API.

Summary

Routing is a core concept in ASP.NET Core Web API. It defines how requests are mapped to actions and ensures your API endpoints are clear and consistent. By mastering routing, you can build clean, scalable, and easy-to-use APIs.

VISUAL STUDIO 2026 MADE EASY
Recommended Book

VISUAL STUDIO 2026 MADE EASY

Build real applications with C#, VB.NET, Python, JavaScript, C++, and .NET 10. A practical companion for mastering Visual Studio 2026 step by step.