Labs ICT
โญ Pro Login

Routing and Controllers

Routing is how ASP.NET Core maps incoming HTTP requests to the right code that handles them. When a user hits /api/books/5, routing figures out which method should run. Let me break down how it works.

How Routing Works

In minimal APIs, you define routes directly in Program.cs:

// Simple routes
app.MapGet("/api/users", GetAllUsers);
app.MapPost("/api/users", CreateUser);
app.MapGet("/api/users/{id}", GetUserById);

The route template is the string after MapGet or MapPost. The {id} part is a route parameter โ€” it captures a value from the URL and passes it to your method.

Route Parameters

// Single parameter
app.MapGet("/api/books/{id}", (int id) =>
{
    var book = books.FirstOrDefault(b => b.Id == id);
    return book is not null ? Results.Ok(book) : Results.NotFound();
});

// Multiple parameters
app.MapGet("/api/{category}/{slug}", (string category, string slug) =>
{
    return Results.Ok(new { Category = category, Slug = slug });
});

Route parameters are always enclosed in curly braces. ASP.NET Core automatically converts the string value from the URL to the parameter type (int, string, etc.).

Route Constraints

You can restrict what values a route parameter accepts:

// Only matches if id is a number
app.MapGet("/api/products/{id:int}", (int id) => { ... });

// Only matches if slug is a string
app.MapGet("/api/posts/{slug:string}", (string slug) => { ... });

// Required length
app.MapGet("/api/codes/{code:length(6)}", (string code) => { ... });

// Range constraint
app.MapGet("/api/pages/{number:min(1)}", (int number) => { ... });

Constraints help prevent invalid requests from reaching your code. If someone tries to hit /api/products/abc with an int constraint, it will not match.

HTTP Methods

Each route is tied to an HTTP method:

  • MapGet โ€” retrieve data
  • MapPost โ€” create new data
  • MapPut โ€” update existing data (full replacement)
  • MapPatch โ€” partially update data
  • MapDelete โ€” remove data
app.MapPut("/api/books/{id}", (int id, Book updatedBook) =>
{
    var book = books.FirstOrDefault(b => b.Id == id);
    if (book is null) return Results.NotFound();

    book.Title = updatedBook.Title;
    book.Author = updatedBook.Author;
    book.Price = updatedBook.Price;

    return Results.Ok(book);
});

Grouping Routes

When you have many endpoints, group them with MapGroup:

var bookRoutes = app.MapGroup("/api/books");

bookRoutes.MapGet("/", () => books);
bookRoutes.MapGet("/{id}", (int id) => { ... });
bookRoutes.MapPost("/", (Book book) => { ... });
bookRoutes.MapPut("/{id}", (int id, Book book) => { ... });
bookRoutes.MapDelete("/{id}", (int id) => { ... });

This keeps your code organized and avoids repeating /api/books everywhere.

๐Ÿงช Quick Quiz

What does {id} in a route template represent?