8. Routing

Routing maps a URL to a controller action. The default convention route is {controller=Home}/{action=Index}/{id?}, so /Students/Details/3 runs the Details action of StudentsController with id equal to 3. You can also use attribute routing to place the route directly on the action.

Key points

  • Convention routing is set once in Program.cs.
  • Attribute routing uses [Route] or [HttpGet("path")] above actions.
  • Route parameters like {id} are passed to action method parameters by name.
  • Constraints such as {id:int} reject values of the wrong type.

Example: Convention route in Program.cs

Program.cs
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
Show explanation

/ goes to Home/Index. /Students goes to Students/Index. /Students/Details/3 goes to Students/Details with id 3.

Example: Attribute routing

Controllers/StudentsController.cs
[Route("students")]
public class StudentsController : Controller
{
    [HttpGet("")]
    public IActionResult Index() => View();

    [HttpGet("{id:int}")]
    public IActionResult Details(int id) => View();
}
Show explanation

Now /students shows the list and /students/5 shows one student. A value like /students/abc does not match.