liveBook · Manning

Url generation

As explained in Pro ASP.NET Core 7, Tenth Edition

URL generation is the programmatic construction of resource or endpoint URLs from application configuration and routing information.

URL generation constructs links and endpoint URLs from ASP.NET Core routing configuration instead of embedding URL patterns directly in application code. Razor views can use the asp-action tag helper to create links to controller actions, while endpoint code can use named routes and LinkGenerator to create paths from route values. section 3.2.4 section 13.1.6

Use framework-managed URL generation to keep links aligned with routing decisions:

  • Add asp-action="RsvpForm" to an anchor in an MVC view; Razor renders an href such as /Home/RsvpForm for the current controller. section 3.2.4
  • Name a target route with RouteNameMetadata so generated links select the intended endpoint rather than merely the best matching route. section 13.1.6
  • Obtain LinkGenerator through dependency injection and call GetPathByRouteValues with HttpContext, the route name, and segment values. section 13.1.6
  • Change a route pattern without rewriting the code that generates its URL; the named route can move from /population/{city} to /size/{city}. section 13.1.6

Redirecting from a capital endpoint

A request to /capital/monaco reaches the Capital endpoint. The endpoint obtains LinkGenerator from request services, generates a path for the named population route with city="monaco", and uses that URL for the redirect. Changing the route pattern to size/{city} preserves the generation code while changing the resulting destination.

How Pro ASP.NET Core 7, Tenth Edition covers it

How deep it goes
Demonstrates tag-helper markup, route naming, dependency-injected LinkGenerator calls, and route-pattern changes.
Examples
Uses an RSVP action link, named population and capital endpoints, Monaco route values, and a changed population URL pattern.
What it assumes
Assumes ASP.NET Core views or endpoints, while introducing tag-helper attributes, route metadata, dependency injection access, and route values.
What you can do after
Apply it via asp-action and LinkGenerator to create links that continue working when route patterns change.
How it connects
Connects ASP.NET Core routing with Razor views, tag helpers, minimal APIs, dependency injection, route names, and route values.

Also explained in

Compare how 2 books explain url generation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Pro ASP.NET Core 7, Tenth Edition. The section links point to the parts of the book it draws on.