8.6 — Route Tokens, Named Routes and Link Generation¶
← Roadmap · Section: 8. Routing Prev: 8.5 Route constraints · Next: 8.7 Endpoint precedence
Markers: ⭐ · Confidence: 🔴 · Last reviewed: —
TL;DR¶
Link generation is building a URL from route information instead of concatenating strings, so changing a route template does not break every link to it.
LinkGeneratorworks anywhere, including outside a request.IUrlHelperworks inside controllers.- Named routes (
Name = "GetOrder") give you a stable handle that survives template changes. [controller]and[action]tokens keep templates in sync with class and method names.
Definitions¶
| Term | What it is | What it means |
|---|---|---|
| Link generation | a process | Producing a URL from a route name or controller/action plus values. |
LinkGenerator |
a class | Generates URLs. Works anywhere — a singleton, no HttpContext needed. |
IUrlHelper |
an interface | The controller-scoped equivalent. Url.Action(...). |
| Named route | Name = "..." on an attribute |
A stable identifier for an endpoint, independent of its template. |
| Route token | [controller], [action], [area] |
Replaced at startup with the corresponding name. |
CreatedAtRoute |
a method | Returns 201 with a Location header built from a named route. |
CreatedAtAction |
a method | The same, using a controller and action name instead. |
GetPathByName |
a method | Relative path from a route name. /api/orders/42. |
GetUriByName |
a method | Absolute URL, including scheme and host. |
| Ambient values | the current request's route values | Reused automatically by IUrlHelper when generating a link. |
The concept¶
Why not just build the string?¶
That works until someone changes the route template — adds a version segment, moves the controller, introduces an area. Then every hard-coded string in the codebase is silently wrong, and nothing fails at compile time. You find out when a link 404s in production.
Link generation asks the router instead:
// ✓ Ask the routing system what the URL is
var url = linkGenerator.GetPathByName("GetOrder", new { id = order.Id });
Change the template and the generated URL changes with it.
A picture: a phone directory versus a number written on a napkin. Both work today. When the number changes, only one of them updates.
The other half: tokens¶
The same idea applied to the template itself:
[controller] is replaced at startup with the class name minus its Controller suffix. Rename
the class and the route follows.
How it works¶
The simple version — tokens¶
| Token | Replaced with |
|---|---|
[controller] |
Controller name without the Controller suffix |
[action] |
Action method name |
[area] |
Area name (8.8) |
[Route("api/[controller]")] // api/orders
public class OrdersController : ControllerBase
{
[HttpGet("{id:guid}")] // api/orders/{id}
public IActionResult Get(Guid id) { }
}
⚠️ [action] is rarely right for APIs. REST URLs are nouns describing resources, not verbs
describing methods — GET /api/orders/{id}, not GET /api/orders/get/{id}. And it means renaming
a method silently changes your public API. It suits conventional MVC sites, not APIs.
Named routes¶
[HttpGet("{id:guid}", Name = "GetOrder")]
public async Task<IActionResult> Get(Guid id, CancellationToken ct) { }
The name is a stable handle independent of the template. Change {id:guid} to
orders/{id:guid}/detail and everything referring to "GetOrder" still works.
⚠️ Route names must be globally unique. Two endpoints sharing a name throw at startup, which
is at least a loud failure. A convention like "Orders_Get" avoids collisions in a large API.
Generating links in a controller¶
[HttpPost]
public async Task<IActionResult> Create(CreateOrderRequest request, CancellationToken ct)
{
var order = await _orders.CreateAsync(request, ct);
// 201 Created, with a Location header pointing at the new resource
return CreatedAtRoute("GetOrder", new { id = order.Id }, order);
}
CreatedAtRoute does two things at once: sets the 201 status and builds the Location header
from the named route. That is the correct REST response for a creation
(10.3).
The alternatives:
CreatedAtAction(nameof(Get), new { id = order.Id }, order); // by action name
Url.Action(nameof(Get), "Orders", new { id = order.Id }); // just the URL
Url.RouteUrl("GetOrder", new { id = order.Id }); // by route name
Url.Link("GetOrder", new { id = order.Id }); // ABSOLUTE URL
nameof(Get) is worth using over the string "Get" — renaming the method then updates the
reference, and a typo becomes a compile error.
How it actually works — LinkGenerator¶
IUrlHelper only exists inside a controller. LinkGenerator works anywhere — a background
service, a domain event handler, an email builder:
public class OrderEmailService(LinkGenerator links, IOptions<AppOptions> options)
{
public string BuildConfirmationEmail(Order order)
{
// No HttpContext — so scheme and host must be supplied
var url = links.GetUriByName(
endpointName: "GetOrder",
values: new { id = order.Id },
scheme: "https",
host: new HostString(options.Value.PublicHost));
return $"View your order: {url}";
}
}
⚠️ That is the key difference. Without an HttpContext there is no current scheme or host, so
you must supply them. Getting the public host from configuration matters — behind a reverse proxy
the request's host may be an internal name
(4.2).
With a context available, they are inferred:
LinkGenerator is a singleton, so it is safe to inject anywhere
(6.3).
⚠️ Ambient values¶
IUrlHelper reuses route values from the current request when you do not supply them:
// Currently handling /api/v2/orders/42
var url = Url.Action("List"); // → /api/v2/orders — the v2 was inherited
That is convenient and occasionally surprising: a value you did not mention can leak into the generated URL. In an application with areas or versioned routes it produces links that work in one context and not another.
LinkGenerator does not do this — it uses only what you pass, which makes it more
predictable. That is a reason to prefer it even inside controllers when the URL must be exact.
To clear an ambient value explicitly, pass null:
Link generation and constraints¶
⚠️ Constraints run during generation too (8.5). Supplying a value that fails a constraint produces null, not an exception:
// The route is orders/{id:guid}
var url = links.GetPathByName("GetOrder", new { id = "not-a-guid" });
// url is null — silently
Then $"Click here: {url}" produces "Click here: " and nobody notices until a user reports a
broken email.
Check the result:
var url = links.GetPathByName("GetOrder", new { id = order.Id })
?? throw new InvalidOperationException(
$"Could not generate a URL for order {order.Id}.");
A custom constraint can distinguish the two directions:
public bool Match(..., RouteDirection routeDirection)
{
if (routeDirection == RouteDirection.UrlGeneration)
return true; // do not constrain outgoing links
return Pattern.IsMatch(value);
}
The deeper detail — extra values become query string¶
Values that do not match a route parameter are appended as query parameters:
// Route: orders/{id}
links.GetPathByName("GetOrder", new { id = 42, includeLines = true });
// → /orders/42?includeLines=True
Useful, and worth knowing so you are not surprised by a query string you did not intend.
⚠️ Note the casing — True, not true, because it is bool.ToString(). If a client is
case-sensitive about it, pass a string.
Code¶
A controller doing it properly throughout:
[ApiController]
[Route("api/[controller]")]
public class OrdersController(IOrderService orders, LinkGenerator links) : ControllerBase
{
[HttpGet("{id:guid}", Name = "Orders_Get")] // prefixed name avoids collisions
public async Task<IActionResult> Get(Guid id, CancellationToken ct)
=> await orders.GetAsync(id, ct) is { } order ? Ok(order) : NotFound();
[HttpGet(Name = "Orders_List")]
public async Task<IActionResult> List(
[FromQuery] int pageNumber = 1, CancellationToken ct = default)
{
var result = await orders.ListAsync(pageNumber, ct);
// Build paging links rather than hard-coding them
var next = result.HasMore
? links.GetPathByName(HttpContext, "Orders_List",
new { pageNumber = pageNumber + 1 })
: null;
return Ok(new { result.Items, NextPage = next });
}
[HttpPost]
public async Task<IActionResult> Create(CreateOrderRequest request, CancellationToken ct)
{
var order = await orders.CreateAsync(request, ct);
// 201 + Location header, generated from the route name
return CreatedAtRoute("Orders_Get", new { id = order.Id }, order);
}
}
And outside a request, where the host has to come from configuration:
public class OrderNotificationService(
LinkGenerator links,
IOptions<AppOptions> options,
IEmailSender email)
{
public async Task SendConfirmationAsync(Order order, CancellationToken ct)
{
// No HttpContext in a background service — supply scheme and host explicitly
var url = links.GetUriByName(
"Orders_Get",
new { id = order.Id },
scheme: "https",
host: new HostString(options.Value.PublicHost))
?? throw new InvalidOperationException(
$"Failed to generate a link for order {order.Id}.");
await email.SendAsync(order.CustomerEmail, "Order confirmed",
$"View your order here: {url}", ct);
}
}
Three deliberate choices: the public host comes from configuration rather than the request, the null result is checked rather than silently producing a broken link, and the route name is used so changing the template does not break the email.
Interview questions¶
Q: Why generate links rather than building URL strings?
Because a hard-coded string is silently wrong the moment a route template changes — adding a version segment or moving a controller breaks every link, with no compile error and no failure until someone clicks one. Link generation asks the routing system for the URL, so it stays correct. It also handles the details you would otherwise get wrong: URL encoding, the path base when the app is hosted in a subfolder, and appending extra values as query parameters.
Q: What is the difference between LinkGenerator and IUrlHelper?
IUrlHelper is scoped to a controller and reuses ambient route values from the current request,
so Url.Action("List") inherits things like the current API version without you asking.
LinkGenerator is a singleton usable anywhere, including background services and domain event
handlers where there is no HttpContext — but without a context it cannot infer scheme and host,
so you supply them. I would take the public host from configuration rather than the request,
because behind a reverse proxy the request's host may be an internal name. LinkGenerator is also
more predictable, since it uses only the values you pass.
Q: What are route names for?
They give an endpoint a stable identifier independent of its URL template, so code referring to
"GetOrder" keeps working when the template changes. That is what CreatedAtRoute uses to build
the Location header on a 201 response. Names must be globally unique across the application —
duplicates throw at startup — so a prefixed convention like Orders_Get is worth adopting in a
large API.
Q: What happens if link generation fails?
It returns null rather than throwing, which is the trap. Route constraints run during
generation too, so passing a value that fails one — a non-GUID where the template says
{id:guid} — silently produces null. Then string-interpolating it into an email gives you a
message with a missing link and no error anywhere. So I check the result and throw with a useful
message, because a loud failure at generation time is far better than a broken link a customer
discovers.
Traps ⚠️¶
- Link generation returns null on failure, not an exception. Check the result.
- Constraints run during generation, so a value failing one silently produces null.
IUrlHelperreuses ambient route values, so a value you did not supply can leak into the URL.- Route names must be globally unique. Duplicates throw at startup.
LinkGeneratoroutside a request has no scheme or host. Supply them from configuration, not from the request.[action]in an API template means renaming a method changes a public URL.- Extra values become query string parameters, with
bool.ToString()casing —True, nottrue. - Hard-coded URL strings do not fail at compile time. They fail in production.
Related¶
- 8.3 Conventional vs attribute routing — where tokens are used
- 8.5 Route constraints —
RouteDirectionduring generation - 8.4 Route templates — why
{**path}round-trips - 8.8 Areas — the
[area]token - 10.3 Status codes — 201 and the
Locationheader - 10.1 REST principles — HATEOAS and generated links
- 4.2 Hosting model — why the request host may be wrong