Skip to content

8.3 — Conventional vs Attribute Routing

← Roadmap · Section: 8. Routing Prev: 8.2 UseRouting and UseEndpoints · Next: 8.4 Route templates

Markers: 🔥 💻 · Confidence: 🔴 · Last reviewed: —


TL;DR

Two ways to tell ASP.NET Core which URLs map to which actions.

  • Conventional routing — one pattern in Program.cs covering many controllers: {controller}/{action}/{id?}. Suits server-rendered MVC apps.
  • Attribute routing — a [Route] or [HttpGet] attribute on each action. Suits APIs, and is required by [ApiController].
  • For a Web API, use attribute routing. For a traditional MVC site, conventional is less repetitive.

Definitions

Term What it is What it means
Conventional routing a routing style One URL pattern in Program.cs matching many controllers by naming convention.
Attribute routing a routing style Route templates declared as attributes on controllers and actions.
MapControllerRoute a method Registers a conventional route pattern.
MapControllers a method Registers attribute-routed controllers. No pattern needed.
MapDefaultControllerRoute a method Shorthand for the standard {controller=Home}/{action=Index}/{id?} pattern.
[Route] an attribute Sets a route template on a controller or action.
[HttpGet] etc. attributes Constrain the HTTP method, and optionally carry a template.
[controller] token a template token Replaced with the controller name minus the "Controller" suffix.
[ApiController] an attribute Enables API conventions — and requires attribute routing.
Route prefix a controller-level template A [Route] on the controller, prepended to each action's template.

The concept

Two philosophies

Conventional routing says: "URLs follow a pattern, and I will describe the pattern once."

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

That one line routes every controller in the application. /Products/Details/5 finds ProductsController.Details(5) by matching names.

Attribute routing says: "each action declares its own URL."

[HttpGet("api/products/{id:int}")]
public IActionResult Details(int id) { }

The route is written where the action is, so you read one file and know the URL.

A picture: street naming. Conventional routing is a grid system — "the third street north is 3rd Street" — one rule covering the whole city. Attribute routing is naming each street individually. The grid is concise and predictable; individual names handle irregular places better.

Which to use

Attribute routing for APIs. REST URLs do not follow the {controller}/{action} shape — POST /api/orders/{id}/cancel is not an action name pattern — and [ApiController] requires attribute routing anyway.

Conventional routing for server-rendered MVC. A site with dozens of controllers each having Index, Details, Create and Edit actions is exactly what conventions are for. Writing thirty identical [Route] attributes would be pure repetition.

You can use both in one application, which is common: conventional routes for the MVC pages, attribute routes for the API controllers.


How it works

The simple version — conventional

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

Reading the pattern:

Segment Meaning
{controller=Home} Controller name, defaulting to Home
{action=Index} Action name, defaulting to Index
{id?} Optional parameter named id

So:

/                      → HomeController.Index()
/Products              → ProductsController.Index()
/Products/Details      → ProductsController.Details()
/Products/Details/5    → ProductsController.Details(5)

Several patterns can be registered, and they are tried in registration order:

// A specific pattern first
app.MapControllerRoute(
    name: "blog",
    pattern: "blog/{year:int}/{month:int}/{slug}",
    defaults: new { controller = "Blog", action = "Post" });

// The general fallback last
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

⚠️ Order matters, and specific must come first. The default pattern matches almost anything, so registering it first means nothing after it is ever reached.

Attribute routing

[ApiController]
[Route("api/[controller]")]                  // prefix for every action
public class OrdersController : ControllerBase
{
    [HttpGet]                                // GET  /api/orders
    public IActionResult List() { }

    [HttpGet("{id:guid}")]                   // GET  /api/orders/{id}
    public IActionResult Get(Guid id) { }

    [HttpPost]                               // POST /api/orders
    public IActionResult Create(CreateOrderRequest request) { }

    [HttpPost("{id:guid}/cancel")]           // POST /api/orders/{id}/cancel
    public IActionResult Cancel(Guid id) { }

    [HttpGet("~/api/all-orders")]            // ~ ESCAPES the controller prefix
    public IActionResult All() { }
}
app.MapControllers();                        // no pattern — routes come from the attributes

Three things worth pulling out.

The controller [Route] is a prefix, prepended to each action's template.

[controller] is a token replaced with the controller name minus its suffix, so OrdersController becomes orders (8.6). Using the token rather than hard-coding "api/orders" means renaming the controller updates the route.

A leading ~/ escapes the prefix, letting one action opt out of the controller's base path.

⚠️ [ApiController] requires attribute routing

[ApiController]
public class OrdersController : ControllerBase       // ✗ no [Route]
{
    public IActionResult Get() { }
}

That throws at startup:

InvalidOperationException: Action ... does not have an attribute route. Action methods on controllers annotated with ApiControllerAttribute must be attribute routed.

This is deliberate — API URLs should be explicit rather than derived from method names, since renaming a method would otherwise silently change your public API contract. See 10.4.

How it actually works — mixing them

⚠️ An action with an attribute route is invisible to conventional routing. The two systems do not overlap:

public class ProductsController : Controller
{
    public IActionResult Index() { }              // conventional: /Products

    [Route("catalogue")]
    public IActionResult Browse() { }             // ONLY /catalogue — not /Products/Browse
}

/Products/Browse returns 404. Once an action is attribute-routed, the conventional pattern no longer applies to it.

That is a genuine source of confusion when adding one attribute to an otherwise conventional controller.

Mixing at the application level is fine and common:

app.MapControllers();                    // attribute-routed API controllers

app.MapControllerRoute(                  // conventional MVC pages
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

The deeper detail — minimal APIs

A third option, with the route at the registration site:

app.MapGet("/api/orders/{id:guid}", async (Guid id, IOrderService orders, CancellationToken ct)
    => await orders.GetAsync(id, ct) is { } order ? Results.Ok(order) : Results.NotFound());

Same routing system, same endpoint table (8.1). The difference is organisational rather than technical:

Controllers + attributes Minimal APIs
Where the route lives On the action At registration
Grouping By class By MapGroup (8.9)
Filters MVC filters Endpoint filters (12.7)
Model binding Full Slightly reduced
Suits Larger APIs, familiar structure Small services, AOT

Neither is the wrong answer. Controllers give you a conventional structure and the full MVC feature set; minimal APIs are lighter and better suited to Native AOT (21.7).


Code

A realistic API controller:

[ApiController]
[Route("api/v{version:apiVersion}/[controller]")]     // versioned prefix — see 10.6
[Produces("application/json")]
public class OrdersController(IOrderService orders) : ControllerBase
{
    // GET /api/v1/orders?page=1&size=20
    [HttpGet]
    [ProducesResponseType<PagedResult<OrderDto>>(StatusCodes.Status200OK)]
    public async Task<IActionResult> List(
        [FromQuery] int page = 1,
        [FromQuery] int size = 20,
        CancellationToken ct = default)
        => Ok(await orders.ListAsync(page, size, ct));

    // GET /api/v1/orders/{id}
    [HttpGet("{id:guid}", Name = "GetOrder")]         // named, for link generation — see 8.6
    [ProducesResponseType<OrderDto>(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<IActionResult> Get(Guid id, CancellationToken ct)
        => await orders.GetAsync(id, ct) is { } order ? Ok(order) : NotFound();

    // POST /api/v1/orders
    [HttpPost]
    [ProducesResponseType<OrderDto>(StatusCodes.Status201Created)]
    public async Task<IActionResult> Create(CreateOrderRequest request, CancellationToken ct)
    {
        var order = await orders.CreateAsync(request, ct);

        // Uses the route NAME, so the URL is generated rather than hard-coded
        return CreatedAtRoute("GetOrder", new { id = order.Id }, order);
    }

    // POST /api/v1/orders/{id}/cancel — an action, not a resource
    [HttpPost("{id:guid}/cancel")]
    public async Task<IActionResult> Cancel(Guid id, CancellationToken ct)
    {
        await orders.CancelAsync(id, ct);
        return NoContent();
    }
}

Two things worth noticing.

{id:guid} is a constraint, so /api/v1/orders/abc does not match at all and returns 404 rather than reaching the action with an unparseable value (8.5).

CreatedAtRoute with a named route generates the Location header rather than string-concatenating a URL, so changing the route template does not break it (8.6).

And the conventional equivalent, for an MVC site

app.MapControllerRoute(
    name: "areas",
    pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");   // see 8.8

app.MapControllerRoute(
    name: "products",
    pattern: "shop/{category}/{id:int?}",
    defaults: new { controller = "Products", action = "Browse" });

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");                // last — most general

Interview questions

Q: What is the difference between conventional and attribute routing?

Conventional routing defines one or more URL patterns centrally in Program.cs, typically {controller}/{action}/{id?}, and matches requests to actions by naming convention — so one line routes the whole application. Attribute routing puts the route template on the controller or action itself, so each endpoint declares its own URL. Conventional suits server-rendered MVC sites where controllers follow a regular Index/Details/Create shape; attribute routing suits APIs, where REST URLs do not follow that pattern.

Q: Which would you use for a Web API, and why?

Attribute routing. REST URLs like POST /api/orders/{id}/cancel do not fit the controller/action shape, and having the route next to the action makes the API surface readable from the code. It is also not optional in practice — [ApiController] requires attribute routing and throws at startup without it, which is deliberate, because deriving public URLs from method names means renaming a method silently changes your API contract.

Q: Can you mix them?

At the application level yes, and it is common — conventional routes for MVC pages and attribute routes for API controllers in the same app. What you cannot do is mix them for a single action: once an action has a route attribute, conventional routing no longer applies to it. So adding one [Route] to an otherwise conventional controller makes that action reachable only at its attribute URL, and the conventional path returns 404. That catches people out.

Q: What does the [controller] token do?

It is replaced with the controller's name minus the Controller suffix, so [Route("api/[controller]")] on OrdersController produces api/orders. The benefit over hard-coding the string is that renaming the controller updates the route automatically. There is an [action] token too, though it is less useful for APIs since REST URLs are usually nouns rather than method names.


Traps ⚠️

  • [ApiController] without a route attribute throws at startup.
  • An attribute-routed action is invisible to conventional routing. The conventional URL returns 404.
  • Conventional route order matters — the general {controller}/{action} pattern must be registered last.
  • A leading / or ~/ on an action template escapes the controller prefix. Easy to do by accident.
  • [Route] on an action replaces the controller prefix only if it starts with / or ~/ — otherwise it is appended.
  • Two actions with the same template and method throw at startup with an ambiguity error (8.7).
  • Renaming a controller changes the URL when using [controller] — which is usually desirable, and a breaking API change if you did not intend it.
  • Conventional routing derives URLs from method names, so renaming an action changes a public URL.


Sources