Generate Absolute Path using LinkGenerator in ASP.NET Core

Raymond Raymond event 2022-03-28 visibility 4,883
more_vert

It is common to generate an absolute URL in ASP.NET Core applications. For instance, generated absolute URLs can be used in emails, RSS, sitemaps, canonical URLs for SEO, etc. From ASP.NET Core 2.2, LinkGenerator class is introduced in library Microsoft.AspNetCore.Routing. It is different from IUrlHelper as this new generator class can be used outside the context of an executing request. 

There are two sets of methods or extension methods that can be used:

  • GetPathBy*** - used to get relative paths.
  • GetUriBy*** - used to get absolute URI. 

This page provides some examples to generate absolute URLs. 

Dependency injection

To use this class in your code, we need to inject it. LinkGenerator is a singleton service available from DI. It is registered automatically when you call `services.AddRouting();`. All the methods also need to access HttpContext instance for each request, which can be accessed by injecting HttpContextAccessor

services.AddHttpContextAccessor();

Generate absolute URLs for controllers

The following code snippet shows how to generate absolute URLs for controllers.

var id = 1;
var url = linkGenerator.GetUriByAction(httpContext, action: "ActionName", controller: "ControllerName", values: new { routValue1= "routeValue1", id }, host: "kontext.tech");

Generate absolute URLs for Razor pages

var id = 1;
var url = linkGenerator.GetUriByPage(httpContext, page: "MyPage", values: new {area="MyArea", routValue1= "routeValue1", id }, host: "kontext.tech");

References

ASP.NET Core 2.2.0-preview1: Endpoint Routing - .NET Blog

LinkGenerator Class (Microsoft.AspNetCore.Routing) | Microsoft Docs

Routing in ASP.NET Core | Microsoft Docs

More from Kontext
comment Comments
No comments yet.

Please log in or register to comment.

account_circle Log in person_add Register

Log in with external accounts