-
Notifications
You must be signed in to change notification settings - Fork 10.5k
Description
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.