Routing in ASP.NET Core Made Easy

Routing is how your ASP.NET Core app decides where to send a request — and it’s one of the most important things to understand when building APIs or MVC apps.

In this post, we’ll break down routing in ASP.NET Core in the most human way possible. No magic, just clean paths.


🛣️ What Is Routing?

Routing maps incoming HTTP requests to endpoints — like controller actions, Razor Pages, or minimal APIs.

ASP.NET Core uses two main routing styles:

  • Conventional Routing
  • Attribute Routing

Let’s explore both.


🧭 Attribute Routing (Most Common for APIs)

With attribute routing, you decorate controllers and actions with [Route] and [HttpGet], [HttpPost], etc.

[ApiController]
[Route("api/products")]
public class ProductsController : ControllerBase
{
    [HttpGet]
    public IActionResult GetAll() => Ok(products);

    [HttpGet("{id}")]
    public IActionResult GetById(int id) => Ok(products.First(p => p.Id == id));
}
  • GET /api/productsGetAll()
  • GET /api/products/5GetById(5)

✅ Clean, RESTful, and predictable.


🧱 Conventional Routing (Better for MVC)

This approach uses patterns defined in Program.cs:

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
  • GET /home/indexHomeController.Index()
  • GET /products/details/3ProductsController.Details(3)

It’s great when you want centralized control or fallbacks.


✨ Route Constraints & Parameters

You can constrain parameters:

[HttpGet("{id:int}")]
public IActionResult GetById(int id) => ...

Or make optional routes:

[HttpGet("{id?}")]
public IActionResult GetOptional(int? id) => ...

🧩 Combining Routes

You can combine [Route] with method-specific attributes:

[Route("api/users")]
public class UsersController : ControllerBase
{
    [HttpGet("{id}")]
    public IActionResult Get(int id) => ...
}

Or simplify it:

[HttpGet("api/users/{id}")]
public IActionResult Get(int id) => ...

⚠️ Routing Gotchas

  • Match order matters (especially with overlapping paths)
  • Don’t mix conventional + attribute routing on the same controller
  • Use [ApiController] for auto model validation and cleaner APIs

✅ Up Next

Now that routes are no longer a mystery, let’s jump into Dependency Injection — the backbone of flexibility in ASP.NET Core apps.

➡️ Dependency Injection Demystified →

Keep following the series — it’s all clicking into place 🚀

0
Subscribe to my newsletter

Read articles from Esanju Babatunde directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Esanju Babatunde
Esanju Babatunde