Microsoft Docs

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

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:

TokenDescription
{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 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:

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:

  1. Update routing configuration to MapControllerRoute.
  2. Replace RouteConfig.cs with Program.cs code.
  3. Convert Web Forms or old .aspx pages to Razor Pages or MVC views.
  4. Review attribute routes for any legacy patterns.