Aspnet Routing
title: ASP.NET Core Routing — Complete Guide to URL Routing description: 'Learn ASP.NET Core routing: convention-based routing, attribute routing, route constraints, route parameters, endpoint routing, and area routing for complex apps.' date: 2026-06-28 lastmod: 2026-06-28 weight: 18 tags: [backend, aspnet]
ASP.NET Core routing maps incoming HTTP requests to controller actions or endpoint handlers, supporting convention-based patterns, attribute routing, route constraints, and custom route parameters.
## What You'll Learn
By the end of this tutorial, you'll configure convention routing, use attribute routing with constraints, create custom route parameters, organize routes with areas, and understand endpoint routing.
## Real-World Use
A multi-tenant SaaS app routes requests based on subdomain: tenant1.myapp.com/products routes to specific tenant controllers with customer ID extracted from the URL.
## Routing Learning Path
```mermaid
flowchart LR
A[Models] --> B[Routing]
B --> C[Middleware]
C --> D[DI]
D --> E[Config]
B --> F{You Are Here}
style F fill:#f90,color:#fff
Convention-Based Routing
var app = builder.Build();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
// Multiple routes
app.MapControllerRoute(
name: "areas",
pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
app.MapControllerRoute(
name: "blog",
pattern: "blog/{year:int}/{month:int}/{slug}",
defaults: new { controller = "Blog", action = "Post" });
Attribute Routing
[Route("api/products")]
[ApiController]
public class ProductsController : ControllerBase
{
[HttpGet] // GET /api/products
public IActionResult GetAll() { ... }
[HttpGet("{id:int}")] // GET /api/products/5
public IActionResult GetById(int id) { ... }
[HttpPost] // POST /api/products
public IActionResult Create(Product product) { ... }
[HttpPut("{id}")] // PUT /api/products/5
public IActionResult Update(int id, Product product) { ... }
[HttpDelete("{id}")] // DELETE /api/products/5
public IActionResult Delete(int id) { ... }
}
Route Constraints
[HttpGet("{id:int}")] // Only integers
[HttpGet("{id:guid}")] // Only GUIDs
[HttpGet("{slug:alpha}")] // Only letters
[HttpGet("{slug:regex(^[a-z0-9-]+$)}")] // Custom regex
[HttpGet("{page:int:min(1)}")] // Integer >= 1
[HttpGet("{date:datetime}")] // Valid DateTime
// Custom constraint
public class EvenNumberConstraint : IRouteConstraint
{
public bool Match(HttpContext ctx, IRouter router,
string routeKey, RouteValueDictionary values,
RouteDirection direction)
{
if (values.TryGetValue(routeKey, out var value) && int.TryParse(value?.ToString(), out int id))
return id % 2 == 0;
return false;
}
}
// Register in Program.cs
builder.Services.AddRouting(options =>
options.ConstraintMap.Add("even", typeof(EvenNumberConstraint)));
Endpoint Routing
// Modern approach (.NET 6+)
app.UseRouting(); // Matches endpoints
app.UseAuthorization(); // Middleware between routing and endpoints
app.MapControllers(); // Maps controller endpoints
// Minimal API endpoints
app.MapGet("/api/status", () => Results.Ok(new { Status = "Healthy" }));
app.MapPost("/api/orders", async (Order order, IOrderService service) =>
{
var result = await service.CreateAsync(order);
return Results.Created($"/api/orders/{result.Id}", result);
});
Area Routing
// Admin area registration
[Area("Admin")]
[Route("admin/[controller]/[action]")]
public class DashboardController : Controller
{
public IActionResult Index() => View();
}
// Area route configuration
app.MapControllerRoute(
name: "areas",
pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
Common Mistakes
1. Route Order Ambiguity
More specific routes must be registered before general ones. The first match wins.
2. Missing Route Constraints
Without constraints, /products/abc matches {id:int} and causes conversion errors.
3. Not Using Areas in Large Apps
Without areas, controllers with the same name conflict. Areas provide namespacing for routes.
4. Hardcoding URLs in Views
Use Tag Helpers (asp-controller, asp-action) and URL helpers instead of hardcoded paths.
5. Mixing Convention and Attribute Routing
Choose one approach per controller. Convention routing uses the pattern. Attribute routing is explicit on each action.
Practice Questions
1. What is the difference between convention and attribute routing?
Convention routing uses a global pattern. Attribute routing puts route templates directly on controllers and actions with [Route] attributes.
2. How do route constraints work?
Constraints like :int, :guid, :regex filter which values match a route parameter. /products/abc doesn't match {id:int}.
3. What is endpoint routing?
Endpoint routing decouples route matching from middleware execution. Middleware sits between UseRouting() and endpoint execution.
4. How do you handle optional route parameters?
Use ? suffix (id?) or provide default values in the route pattern.
5. Challenge: Create routes for a blog with posts, categories, and tags.
[Route("blog")]
public class BlogController : Controller
{
[HttpGet] public IActionResult Index() { ... }
[HttpGet("category/{category}")] public IActionResult ByCategory(string category) { ... }
[HttpGet("tag/{tag}")] public IActionResult ByTag(string tag) { ... }
[HttpGet("{year:int}/{month:int}/{slug}")] public IActionResult Post(int year, int month, string slug) { ... }
}
FAQ
{{< faq "How do I handle 404 routes?" "Add a catch-all route at the end: app.MapFallbackToController(\"Index\", \"Home\")." >}}Mini Project: Blog Routes
Configure complete routing for a blog application with convention and attribute routes.
// Program.cs
app.MapControllerRoute("blog", "blog/{year:int}/{month:int}/{slug}",
new { controller = "Blog", action = "Post" });
app.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
// BlogController.cs
[Route("blog")]
public class BlogController : Controller
{
public IActionResult Index() => Content("Blog Home");
[HttpGet("tag/{tag}")]
public IActionResult Tag(string tag) => Content($"Tag: {tag}");
}
What's Next
ASP.NET Core Middleware ASP.NET Core Dependency Injection
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro