How does routing work in ASP.NET MVC? Explain attribute routing.
How does routing work in ASP.NET MVC? Explain attribute routing.
146
11-Jun-2025
ICSM Computer
18-Jun-2025In ASP.NET MVC, routing is the mechanism that maps incoming URLs to controller actions. It’s essential to delivering requests to the right code based on URL patterns.
1. Routing Table (Convention-Based Routing)
Defined in
RouteConfig.cs(insideApp_Start).The application uses URL patterns to route requests.
Example:
URL:
/Products/Details/5→Maps to:
ProductsController.Details(int id = 5)2. Route Matching Process
When a request comes in:
What is Attribute Routing?
Attribute Routing lets you define routes directly on controller actions using
[Route]attributes instead of relying on the centralized route table.Enabling Attribute Routing
In
RouteConfig.cs:Example: Attribute Routing
URL:
/articles/view/10→ hitsViewArticle(10)URL:
/articles/delete/10→ hitsDeleteArticle(10)Attribute Routing with Constraints
Adds validation to ensure only integers for
yearandmonth.Benefits of Attribute Routing
Summary
{controller}/{action}/{id})[Route]Routing = URL → Controller + Action + Parameters