What is routing in ASP.NET MVC?
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.
// 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));
}
Practise the whole thread the way an interviewer walks it — each question builds on the last.
- What is ASP.NET MVC?
- Explain the ASP.NET MVC request life cycle.
- What is routing in ASP.NET MVC?You are here
- What is ActionResult in ASP.NET MVC?
- What is the difference between ViewBag, ViewData and TempData?
- What is a strongly typed view in ASP.NET MVC?
- How does model validation work in ASP.NET MVC?