Routing to controller actions
Routing decides which controller action runs for a given URL. ASP.NET Core MVC supports conventional routes defined once in Program.cs and attribute routes placed on controllers and actions. This lesson explains both, route parameters and constraints, and how to generate links that stay correct.
- StartURL arrives/products/details/5
- Step 2Template matched{controller=Home}/{action=Index}/{id?}
- Step 3Route valuescontroller = Products, action = Details, id = 5
- EndAction selectedProductsController.Details(int id) runs with id = 5
Routing also works backwards: from route values it can generate the URL for a link.
The idea in plain words
Routing is the part of ASP.NET Core that looks at the incoming URL and decides which code should handle it. In MVC that code is an action on a controller. Routing also works in reverse: given a controller and action, it can build the URL for you, so your links do not break when routes change.
There are two styles. Conventional routing defines a pattern once, such as controller, then action, then id, and every controller follows it. Attribute routing puts the URL template directly on the controller or action with the [Route] or [HttpGet] attributes. Apps that render pages often use conventional routes, while APIs usually use attribute routes. You can mix both in one app.
Conventional routes
A route template is made of literal text and parameters in braces. The template {controller=Home}/{action=Index}/{id?} has three parameters. The equals sign gives a default value and the question mark makes a parameter optional. So the URL / runs HomeController.Index, /products runs ProductsController.Index, and /products/details/7 runs ProductsController.Details with id 7.
You can add more specific routes before the default one. Routes with literal segments, such as blog/{slug}, are good for friendly URLs.
app.MapControllerRoute(
name: "blog",
pattern: "blog/{slug}",
defaults: new { controller = "Blog", action = "Article" });
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");Attribute routes
With attribute routing the template lives next to the code that handles it, which makes it easy to see which URL reaches which action. A [Route] on the controller acts as a prefix for every action. The token [controller] is replaced with the controller name without the Controller suffix. Constraints such as :int restrict what a parameter can match, so /orders/abc does not reach an action that expects a number.
- {id:int} only matches whole numbers.
- {id?} makes the parameter optional.
- [HttpGet] and [HttpPost] limit the HTTP method as well as setting the template.
[Route("[controller]")]
public class OrdersController : Controller
{
// GET /orders
[HttpGet("")]
public IActionResult Index() => View();
// GET /orders/42
[HttpGet("{id:int}")]
public IActionResult Details(int id) => View(id);
// POST /orders/42/cancel
[HttpPost("{id:int}/cancel")]
public IActionResult Cancel(int id) => RedirectToAction(nameof(Details), new { id });
}Generating links
Never hand-write URLs like href="/orders/42" in views. Use the anchor Tag Helper or Url.Action so routing builds the link. If you later change a route template, every generated link updates automatically.
<a asp-controller="Orders" asp-action="Details" asp-route-id="42">View order</a>
@* Produces: <a href="/orders/42">View order</a> *@Common mistakes
Routing problems usually show up as a 404 or as an AmbiguousMatchException.
- Placing a general route before a specific one, so the specific one never matches. Add specific conventional routes first.
- Two actions with the same template and HTTP method, which causes an ambiguous match error.
- Forgetting that an action with attribute routes is no longer reachable through conventional routes.
- Using route constraints for input validation. Constraints help pick a route; validate input with model validation instead.
Going further
Areas add another route parameter so large apps can be split into sections such as Admin. Route values like {controller} and {action} are also available inside filters and middleware. Later lessons on areas and the anchor Tag Helper build on what you learned here.
Interview question
When would you choose attribute routing over conventional routing?
Attribute routing is a good choice when URLs do not follow one uniform pattern, for example REST APIs with nested resources like /orders/42/items, or when you want each action's URL visible right next to its code. Conventional routing suits page-based apps where most URLs follow controller/action/id. Both can be used in the same app, but an action that has attribute routes can only be reached through them.
Want the full details? Read the official Microsoft documentation for this topic.