In ASP.NET Core 10, how do you build an e-mail link from a background job with LinkGenerator, and how do GetPathByName and GetUriByName differ?
answer
- singleton in DI, no request needed
- GetPath* = path, GetUri* = scheme + host
- HttpContext overloads add ambient values
- returns null when nothing matches
- host from configuration, not the request
basics
~20 sInject LinkGenerator, a DI singleton, and call GetUriByName with the endpoint name, route values, a scheme and a host taken from configuration. GetPathByName returns only the path; GetUriByName returns an absolute URI. Both return null when no endpoint matches.
solid answer
~40 s`LinkGenerator` is registered as a singleton and does not need an `HttpContext`, so a hosted service can inject it. `GetPathByName("GetBooking", new { id })` returns a path like `/bookings/42`. `GetUriByName("GetBooking", new { id }, "https", new HostString("rentals.example.com"))` returns `https://rentals.example.com/bookings/42`; without a request, scheme and host are required parameters. Overloads that take an `HttpContext` fill in the request's ambient route values, path base, scheme and host instead. Every method returns `string?` and yields `null`, not an exception, when no endpoint fits, so check it. For e-mails, take the host from configuration: the docs warn that `GetUri*` with an unvalidated `Host` header echoes untrusted input into links. `IUrlHelper` is no alternative here because it needs an action context.
code
csharp · 15 linesvar app = WebApplication.CreateBuilder(args).Build();
app.MapGet("/bookings/{id:int}", (int id) => Results.Ok(new { id }))
.WithName("GetBooking");
app.MapGet("/debug/links/{id:int}", (int id, HttpContext ctx, LinkGenerator links) => new
{
path = links.GetPathByName("GetBooking", new { id }), // "/bookings/42"
fromRequest = links.GetUriByName(ctx, "GetBooking", new { id }), // request scheme + host
forEmail = links.GetUriByName("GetBooking", new { id },
"https", new HostString("rentals.example.com")), // fixed public host
missing = links.GetPathByName("NoSuchEndpoint", new { id }) // null
});
app.Run();go deeper
Recall that LinkGenerator is injected from DI and turns an endpoint name plus values into a URL.
Explain GetPath* versus GetUri*, the HttpContext and non-HttpContext overloads, and that failure returns null.
Generate links outside requests with explicit scheme, host and path base from configuration, guard against Host-header injection, and treat null results as defects.
Own a single source of truth for the public base URL across services, so e-mails, webhooks and APIs never derive it from incoming requests.
## LinkGenerator in one paragraph `LinkGenerator` is endpoint routing's URL generator. `AddRouting` registers it as a **singleton**, and the routing docs state that it "can be used outside of the context of an executing request". MVC's `IUrlHelper`, tag helpers and action results all call it internally. Its methods take an **address**: an endpoint name (from `WithName` or a route `Name`), or controller/action or page values through the MVC extension methods. ## The method families | Method | Address | Output | |---|---|---| | `GetPathByName` | endpoint name | absolute path, such as `/bookings/42` | | `GetUriByName` | endpoint name | absolute URI with scheme and host | | `GetPathByAction` / `GetUriByAction` | action, controller | path / URI to a controller action | | `GetPathByPage` / `GetUriByPage` | Razor Page name | path / URI to a page | Each comes in two shapes: - **With `HttpContext`**: the current request supplies ambient route values, `PathBase`, scheme and host unless you override them. The action and page variants reproduce `IUrlHelper`'s special handling of `controller`, `action` and `page`. - **Without `HttpContext`**: nothing is ambient. For `GetUri*`, `scheme` and `host` become **required** parameters; `pathBase` defaults to empty. All of them return `string?`. When no endpoint matches the address and values, the result is **`null`**; nothing throws. Production code should treat `null` as a bug and log or fail loudly. ## E-mailing a booking link from a background job A bike-rental app sends a reminder an hour before each booking starts. The work runs in a `BackgroundService`, where there is no request: ```csharp public sealed class ReminderSender( LinkGenerator links, IOptions<PublicSiteOptions> site, IMailer mailer) { public async Task SendAsync(Booking booking, CancellationToken ct) { var url = links.GetUriByName( "GetBooking", new { id = booking.Id }, scheme: "https", host: new HostString(site.Value.Host)) // e.g. "rentals.example.com" ?? throw new InvalidOperationException("No endpoint named GetBooking."); await mailer.SendAsync(booking.Email, $"Your bike is ready: {url}", ct); } } ``` The endpoint it targets is named once: ```csharp app.MapGet("/bookings/{id:int}", (int id) => ...).WithName("GetBooking"); ``` ## Where the host must come from The docs warn about `GetUri*` methods: in an app that does not validate the `Host` header, untrusted request input can be sent back to the client in generated URIs. In a request, the `HttpContext` overloads take the host from that header. For e-mails this is worse, because the link leaves the site in a trusted channel: a forged `Host` on the request that triggers a password-reset or booking e-mail could point the link at an attacker's domain. So: 1. Read the public host and scheme from configuration, as above. 2. Restrict accepted hosts with host filtering in production. 3. If the app is mounted under a path prefix, pass that `pathBase` explicitly, since there is no request to provide it. ## Path base When the app is mounted under a prefix, for example behind a proxy at `/rentals`, the `HttpContext` overloads include the request's `PathBase` automatically, so links come out as `/rentals/bookings/42`. The overloads without `HttpContext` know nothing about it: `GetPathByName("GetBooking", new { id }, pathBase: "/rentals")` or the `pathBase` argument of `GetUriByName` must supply it, typically from the same configuration section as the host. Forgetting it produces links that work in development and 404 in production. ## Why not IUrlHelper? `IUrlHelper` is created by `IUrlHelperFactory.GetUrlHelper(ActionContext)`. It exists inside controllers, Razor Pages and views, tied to the current action context. A background job has none, so `LinkGenerator` is the tool there and in middleware, Minimal API handlers and plain services. ## Troubleshooting a null - Check the endpoint name: names are compared case-sensitively. - Check that the values fill every required parameter and satisfy constraints: `new { id = "abc" }` fails `{id:int}`. - Turn on `Trace` logging for `Microsoft.AspNetCore.Routing`; the docs recommend it because the link generator logs each decision. ## What interviewers listen for - `LinkGenerator` is a singleton usable anywhere; `IUrlHelper` needs an action context. - `GetPath*` versus `GetUri*`, and the `HttpContext` versus explicit scheme/host overloads. - `null` on failure. - Host from configuration for links that leave the request.
- What does LinkGenerator return when the endpoint name exists but the values do not satisfy its template?`null`. Every `GetPath*` and `GetUri*` method returns `string?` and signals failure that way rather than throwing. Typical causes are a missing required parameter or a value that fails a constraint, such as a non-integer for `{id:int}`. Check the result and fail loudly, because a null silently becomes an empty link in an e-mail.
- Why should a GetUriByName call that builds e-mail links not rely on the HttpContext overload?That overload takes scheme and host from the current request, and the host comes from the client-supplied `Host` header. If the app does not validate hosts, an attacker can trigger an e-mail whose link points at their own domain. Pass a scheme and host from configuration instead, and enable host filtering as a second line of defence.
- Tries to resolve IUrlHelper inside a BackgroundService to build e-mail links.
- Registers or resolves LinkGenerator as a scoped service tied to a request.
- Expects LinkGenerator to throw when no endpoint matches the supplied values.
- Builds e-mail links with the request's Host header without host validation.
- Assumes GetPathByName includes the scheme and host.