Routing in ASP.NET Core MVC

Routing maps URLs to controller actions. It's the GPS of your app.

60-Second Version: Routing = Receptionist. /products/5 โ†’ "Send to ProductController.Details, id=5". Two types: Conventional = 1 rule for all, Attribute = custom URL per action.

1. Conventional Routing: One Pattern Rules All

Set in Program.cs:

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
URLControllerActionId
/HomeIndexnull
/productProductIndexnull
/product/details/5ProductDetails5

{id?} = optional. =Home = default if missing.

2. Attribute Routing: Custom URLs

Put route directly on action:

public class BlogController : Controller
{
    [Route("blog/{year:int}/{month:int}/{slug}")]
    public IActionResult Post(int year, int month, string slug)
    {
        // Matches: /blog/2026/1/aspnet-core-routing
        return View();
    }
}

Why? SEO-friendly URLs. /blog/2026/1/my-post beats /blog/post?year=2026&month=1&slug=my-post

3. Route Constraints: Filter Bad URLs

{id:int} = only match if id is number. /product/details/abc โ†’ 404, not crash.

ConstraintExampleMatches
:int{id:int}5, 99
:guid{id:guid}UUID only
:alpha{name:alpha}letters only
:min(18){age:min(18)}18+
Beginner Trap: Karan defines [Route("product/{id}")] and [Route("product/{name}")]. Both match /product/5. AmbiguousMatchException. Fix: Add constraints {id:int} vs {name:alpha}.

Quick Check ๐Ÿง 

Next: Models & ViewModels - Entities vs DTOs, Data Annotations, and validation.

Comments on Views & Razor (0)

No comments yet. Be the first to share your thoughts!