What is routing in ASP.NET MVC?

ASP.NET MVC Routing Basic 1–2 Yrs2–3 Yrs Conceptual 1 min read

Quick Answer

Routing is the system that maps an incoming URL to a controller action, and (in reverse) generates URLs for a given action. You define routes either by convention (a pattern like {controller}/{action}/{id?}) or by attributes on the action ([HttpGet("products/{id:int}")]).

Routing is how ASP.NET decides which action handles a URL, and also how it builds URLs for links. There are two ways to define routes. Convention-based routing uses a central pattern like {controller}/{action}/{id?}, so /products/details/5 maps to ProductsController.Details with id 5. Attribute routing puts the route right on the action with something like [HttpGet("products/{id:int}")], which is what I use for APIs because it's explicit and supports constraints. In ASP.NET Core routing is middleware, so once the endpoint is matched, later middleware like authorization can see which action is about to run.

Two styles, often mixed:

  • Convention-based routing — one or more URL templates registered centrally. {controller=Home}/{action=Index}/{id?} means /products/details/5 → ProductsController.Details(5). Order matters; the first match wins.
  • Attribute routing — the route lives next to the action: [Route("api/products/{id:int}")]. Preferred for APIs and for irregular URLs.

Other pieces interviewers ask about:

  • Route constraints — {id:int}, {slug:regex(...)}, {page:min(1)} restrict which URLs match.
  • Route values & defaults — optional segments and default values.
  • URL generation — Url.Action / tag helpers build URLs from route data, so changing a route doesn't break links.
  • Endpoint routing (Core) — routing runs as middleware (UseRouting) and the matched endpoint is available to later middleware like authorization.

C# — convention + attribute routing
// Program.cs — convention route
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

// Attribute routing on a controller
[Route("products")]
public class ProductsController : Controller
{
    [HttpGet("{id:int}")]           // GET /products/5
    public IActionResult Details(int id) => View(_service.Find(id));

    [HttpGet("{slug:regex(^[a-z0-9-]+$)}")] // GET /products/red-widget
    public IActionResult BySlug(string slug) => View(_service.FindBySlug(slug));
}