liveBook · Manning

LinkGenerator

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

LinkGenerator is the ASP.NET Core service that generates URL paths and URLs from route information.

LinkGenerator creates paths and complete URLs from endpoint route information, avoiding hardcoded links that break when route templates change. It can be used in minimal API handlers, middleware, background services, and other application services. section 6.4 section 14.5.3

Generate a path from a named endpoint

Name the target endpoint with WithName("product"), inject LinkGenerator into another handler, and call GetPathByName("product", new { name = "big-widget" }). The generated path follows the endpoint's route template, such as /product/big-widget. section 6.4.1

Use the named-endpoint methods according to the URL you need:

  • Call GetPathByName with route values to generate a path. section 6.4.1
  • Call GetUriByName with a scheme and HostString to generate a complete URL; validate host values before using them. section 6.4.1
  • Use GetPathByPage or GetPathByAction for Razor Pages and MVC actions. section 6.4 section 14.5.3

Endpoint names are case-sensitive and globally unique. Configure RouteOptions to standardize generated URLs with lowercase paths, lowercase query strings, or trailing slashes; pass LinkOptions when one URL needs different conventions. section 6.4.1 section 6.4.3

Figure 6.8 A comparison between routing and URL generation. Routing takes in a URL and generates route values, but URL generation uses route values to generate a URL.
CH06_F08_Lock3

Compare incoming routing, which turns a URL into route values, with URL generation, which combines route values and a template into a URL. section 6.4

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

How deep it goes
Explains named-endpoint generation, route values, complete URLs, ambient request values, and formatting options without descending into routing implementation internals.
Examples
Demonstrates a named product endpoint, GetPathByName, GetUriByName, Razor Page generation, and lowercase or trailing-slash configuration.
What it assumes
Assumes basic ASP.NET Core routing and endpoint knowledge while teaching named endpoints, dependency injection access, and route-value URL generation.
What you can do after
Build it from scratch by naming endpoints, injecting LinkGenerator, supplying route values, and configuring or overriding URL conventions.
How it connects
Connects URL generation with routing, minimal APIs, Razor Pages, MVC, dependency injection, IUrlHelper, RouteOptions, and LinkOptions.

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.