Skip to content

Make it easy to configure a host/scheme for absolute URLs with LinkGenerator #14192

@RehanSaeed

Description

@RehanSaeed

Is your feature request related to a problem? Please describe.

LinkGenerator

LinkGenerator requires the HttpContext to generate a full absolute URL which also contains the scheme, hostname and optional port. Outside of the controller, this means I have to also inject the IHttpContextAccessor into my constructor and pass it in like so:

this.linkGenerator.GetUriByRouteValues(
    this.httpContextAccessor.HttpContext,
    "GetPage",
    new() { First = 1, Last = 10 });

This requires a lot of ceremony and additional noise.

IUrlHelper

IUrlHelper does not require the HttpContext if you add this code to the Startup. We use the IActionContextAccessor and IUrlHelperFactory to register IUrlHelper into the IoC container.

services
    .AddSingleton<IActionContextAccessor, ActionContextAccessor>()
    .AddScoped(x => x
        .GetRequiredService<IUrlHelperFactory>()
        .GetUrlHelper(x.GetRequiredService<IActionContextAccessor>().ActionContext))

Then if you use the following extension method to create your URL's:

public static string AbsoluteRouteUrl(
    this IUrlHelper urlHelper,
    string routeName,
    object routeValues = null) =>
    urlHelper.RouteUrl(routeName, routeValues, urlHelper.ActionContext.HttpContext.Request.Scheme);

Here is the usage:

this.urlHelper.AbsoluteRouteUrl("GetPage", new() { First = 1, Last = 10 });

I think you'll agree this is much nicer.

Describe the solution you'd like

I would like a way to generate URL's without having to inject the IHttpContextAccessor and LinkGenerator just to generate a single URL. Or a way to use IUrlHelper without all the setup code to get it working nicely.

Metadata

Metadata

Assignees

No one assigned

    Labels

    affected-fewThis issue impacts only small number of customersarea-mvcIncludes: MVC, Actions and Controllers, Localization, CORS, most templatesenhancementThis issue represents an ask for new feature or an enhancement to an existing onefeature-routingseverity-minorThis label is used by an internal tool

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions