Routing in ASP.NET Core MVC
Overview
Routing maps incoming HTTP requests to Controller
actions. ASP.NET Core MVC supports two primary routing styles:
- Conventional routing—defines patterns centrally in
Startup.cs
. - Attribute routing—applies route templates directly on controllers and actions.
Conventional Routing
Define routes in Program.cs
(or Startup.cs
for older projects).
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
Key tokens:
Token | Description |
---|---|
{controller} | Name of the controller (without "Controller" suffix) |
{action} | Action method name |
{id?} | Optional parameter |
Attribute Routing
Apply [Route]
and related attributes directly on controllers or actions.
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
[HttpGet]
public IEnumerable<Product> GetAll() => _repo.GetAll();
[HttpGet("{id:int}")]
public ActionResult<Product> Get(int id)
{
var product = _repo.Find(id);
return product == null ? NotFound() : Ok(product);
}
}
Features:
- Route prefixes with
[Route]
on the controller. - HTTP method attributes like
[HttpGet]
,[HttpPost]
. - Inline constraints (e.g.,
{id:int}
).
Route Constraints
Constraints ensure parameters meet specific criteria.
app.MapControllerRoute(
name: "blog",
pattern: "blog/{year:int:min(2000)}/{month:int:range(1,12)}/{slug}",
defaults: new { controller = "Blog", action = "Post" });
Common constraints:
int
,bool
,datetime
min(...)
,max(...)
,range(...)
alpha
,regex(...)
Custom Route Handlers
Implement IRouter
or use endpoint routing middleware for advanced scenarios.
app.MapGet("/hello/{name}", (string name) => $"Hello, {name}!");
Endpoint routing provides a unified model for MVC, Razor Pages, and minimal APIs.
Testing Routing
Use Microsoft.AspNetCore.Mvc.Testing
and WebApplicationFactory
to verify routes.
public async Task Get_Product_ReturnsOk()
{
var client = _factory.CreateClient();
var response = await client.GetAsync("/api/products/5");
response.EnsureSuccessStatusCode();
}
Migrating from ASP.NET MVC
Key migration steps:
- Update routing configuration to
MapControllerRoute
. - Replace
RouteConfig.cs
withProgram.cs
code. - Convert Web Forms or old .aspx pages to Razor Pages or MVC views.
- Review attribute routes for any legacy patterns.