Generate Absolute Path using LinkGenerator in ASP.NET Core

Raymond Tang Raymond Tang 0 5325 4.47 index 3/28/2022

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: "app.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: "app.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

asp.net asp.net-core

Join the Discussion

View or add your thoughts below

Comments