liveBook · Manning

IUrlHelper

As explained in ASP.NET Core in Action, 3e

IUrlHelper is an ASP.NET Core interface that provides methods for generating URLs from routing information within web application components.

IUrlHelper generates application URLs from routing information inside Razor Pages and MVC controllers. Its Url property provides convenient Page() and Action() methods, using the current request when appropriate. section 14.5 section 14.5.1

Choose the method that matches the destination:

  • Call Page() with a Razor Page path and optional route values, such as Url.Page("Currency/View", new { code = "USD" }). section 14.5.1
  • Call Action() with an MVC action and controller name, such as Url.Action("View", "Currency", new { code = "USD" }). section 14.5.2
  • Supply route values that become URL segments when they match route parameters; otherwise, they become query-string data. section 14.5.1

IUrlHelper works only during a request and can reuse ambient values from the current request. This convenience can make identical calls produce different URLs in different pages or controllers. Use LinkGenerator from other application services, where no HttpContext is available, or when unambiguous URL generation is preferred. section 14.5.2 section 14.7

Listing 14.2 Generating a URL using IUrlHelper and the Razor Page name
public class IndexModel : PageModel                                  #1
{
   public void OnGet()
    {
        var url = Url.Page("Currency/View", new { code = "USD" });   #2
    }
}

Shows a PageModel generating a Razor Page URL with a page path and USD route value. section 14.5.1

Listing 14.3 Generating a URL using IUrlHelper and the action name
public class CurrencyController : Controller      #1
{
    [HttpGet("currency/index")]                   #2
    public IActionResult Index()
    {
        var url = Url.Action("View", "Currency",  #3
            new { code = "USD" });                #3
        return Content($"The URL is {url}");      #4
    }
 
    [HttpGet("currency/view/{code}")]
    public IActionResult View(string code)        #5
    {
         /* method implementation*/
    }
}

Shows an MVC controller generating a URL to another action with a controller name and route value. section 14.5.2

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains Page(), Action(), route values, and ambient values, while treating MVC usage briefly.
Examples
Uses Currency/View with a USD code and a CurrencyController action-to-action link.
What you can do after
Apply it via Page() or Action() to generate refactor-aware links from Razor Pages and MVC controllers.
How it connects
Connects URL generation with routing, Razor Pages, MVC controllers, minimal APIs, and LinkGenerator.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.