skip to content

In ASP.NET Core MVC and Razor Pages, when do you use Url.Action, Url.RouteUrl or Url.Page, and what do they return when no route matches?

level: juniorimportance: should knowfreq 40%

answer

  1. IUrlHelper, via the Url property
  2. action/controller, route name, page name
  3. relative path unless a protocol is passed
  4. string?: null on no match
  5. LinkGenerator equivalents for elsewhere

basics

~20 s

Url.Action targets a controller action by name, Url.RouteUrl a named route, and Url.Page a Razor Page by its path name. All return a path such as /bikes/7, an absolute URL when you pass a protocol, and null when nothing matches.

solid answer

~40 s

All three live on `IUrlHelper`, which controllers, Razor Pages and views expose as `Url`. `Url.Action("Details", "Bikes", new { id = 7 })` picks a controller action by action and controller name; `Url.RouteUrl("BikeDetails", new { id = 7 })` picks the endpoint with that route name, which avoids ambiguity when several routes reach one action; `Url.Page("/Bikes/Details", new { id = 7 })` targets a Razor Page by its name, the path under `Pages` without the extension. They return a path relative to the host, such as `/bikes/7`, and include the scheme and host only when you pass a protocol argument (`Url.Link` always does). Each returns `string?`: `null` means no endpoint fits, and in a view that renders as an empty `href`. Outside MVC the matching APIs are `LinkGenerator.GetPathByAction`, `GetPathByName` and `GetPathByPage`.

code

csharp · 12 lines
csharp
public class BikesController : Controller
{
    [HttpGet("bikes/{id:int}", Name = "BikeDetails")]
    public IActionResult Details(int id)
    {
        ViewData["Self"] = Url.RouteUrl("BikeDetails", new { id });               // "/bikes/7"
        ViewData["Share"] = Url.RouteUrl("BikeDetails", new { id }, "https");     // "https://host/bikes/7"
        ViewData["Book"] = Url.Page("/Rentals/Checkout", new { bikeId = id });   // page link
        ViewData["Broken"] = Url.Action("NoSuchAction");                         // null
        return View();
    }
}

go deeper

for a junior

Recall that Url.Action builds a link to a controller action, Url.Page to a Razor Page, and that both return paths you can put in an href.

for a middle

Explain Url.RouteUrl for named routes, how to get absolute URLs, and why a null result renders as an empty link.

for a senior

Pick deterministic, name-based generation where several routes reach one action, and switch to LinkGenerator outside MVC requests.

for a principal

Ban hand-built URLs in views and services so route changes propagate automatically and links are covered by tests.

## IUrlHelper and where it lives `IUrlHelper` is MVC's per-request URL generator. You get it as the `Url` property on `ControllerBase`, `PageModel` and in Razor views and pages. It is created from the current `ActionContext`, so it knows the request's route values and base path, and it calls endpoint routing's `LinkGenerator` underneath. ## The three main methods | Method | Address | Typical use | |---|---|---| | `Url.Action(action, controller, values)` | action and controller names | links between controller actions | | `Url.RouteUrl(routeName, values)` | a route name from `Name = "..."` or `MapControllerRoute(name: ...)` | one specific route, unambiguous | | `Url.Page(pageName, pageHandler, values)` | a Razor Page name such as `/Bikes/Details` | links to pages and page handlers | A bike-rental site might use all three: ```csharp // In BikesController var a = Url.Action("Details", "Bikes", new { id = 7 }); // "/Bikes/Details/7" var r = Url.RouteUrl("BikeDetails", new { id = 7 }); // depends on that route's template var p = Url.Page("/Rentals/Checkout", new { bikeId = 7 }); // "/Rentals/Checkout?bikeId=7" ``` The page example shows a rule worth knowing: if the page's `@page` directive has no `{bikeId}` segment, the value becomes a query parameter. ## Relative or absolute By default these return an **absolute path**, starting with `/` and including the app's path base but no scheme or host. Pass a protocol to get a full URL: - `Url.Action("Details", "Bikes", new { id = 7 }, "https")` gives `https://<current host>/Bikes/Details/7`. - `Url.RouteUrl("BikeDetails", new { id = 7 }, "https")` does the same for a named route. - `Url.Link(routeName, values)` always returns an absolute URL using the request's scheme and host; `CreatedAtRoute` uses it for `Location` headers. The host comes from the incoming request, so the same Host-header caution applies as for `LinkGenerator.GetUri*`. ## When nothing matches Every method returns `string?`. A `null` result means no endpoint fits the address and values, for example a misspelled action, a missing required value, a value that fails a constraint, or ambient values invalidated by the explicit ones. In a Razor view `href="@Url.Action(...)"` with `null` renders an attribute with no URL, so the bug shows up as a dead link rather than an exception. Unit-testing link generation, or checking for `null` in code paths that build important links, avoids shipping that. ## Two more IUrlHelper members - `Url.Content("~/images/bike.png")` turns an app-relative path starting with `~/` into a path that includes the path base; it does not use routing at all. - `Url.IsLocalUrl(returnUrl)` returns `true` only for local URLs, and is the standard check before redirecting to a `returnUrl` taken from a query string, which prevents open redirects after login. Neither generates a route-based link, but both appear next to `Url.Action` in real code and in interviews. ## Choosing between them 1. **Same controller, everyday links**: `Url.Action` with just the action name; ambient values fill the controller. 2. **Several routes reach the same action**, such as a conventional and an attribute route: `Url.RouteUrl` with the route name to pick one. 3. **Razor Pages**: `Url.Page`, never `Url.Action`. 4. **Outside MVC** (middleware, Minimal APIs, background services): inject `LinkGenerator` and use `GetPathByAction`, `GetPathByName` or `GetPathByPage`. ## What interviewers listen for - Which helper addresses what: action names, route names, page names. - Paths by default, absolute URLs with a protocol or `Url.Link`. - `null` on failure and how it shows up in views. - That `IUrlHelper` belongs to MVC requests and `LinkGenerator` covers everything else.

  • Why would you pick Url.RouteUrl over Url.Action when both can reach the same action?
    A route name selects one specific endpoint. If an action is reachable through a conventional route and an attribute route, or through two attribute routes, `Url.Action` picks whichever route the generator tries first that fits the values, which may not be the URL you want. Naming the route and using `Url.RouteUrl` makes the output deterministic.
  • What happens to a value passed to Url.Page that the page's @page template does not declare?
    It is appended to the query string. With `@page "{id:int}"` on an Edit page, `Url.Page("/Edit", new { id = 17 })` gives `/Edit/17`; without that template it gives `/Edit?id=17`, as the routing docs show. The page still receives the value, through the query string.

  • Uses Url.Action to link to a Razor Page.
  • Expects Url.Action to return an absolute URL with scheme and host by default.
  • Assumes Url.Action throws when the action name is misspelled.
  • Resolves IUrlHelper in middleware or a background service instead of LinkGenerator.
  • Hardcodes paths like "/bikes/" + id in views instead of generating them.