Make it easy to configure a host/scheme for absolute URLs with LinkGenerator
- Dominant language
- C#
- Stars
- 38.4k
- Forks
- 10.9k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 281
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:
```c#
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.
```c#
services
.AddSingleton()
.AddScoped(x => x
.GetRequiredService()
.GetUrlHelper(x.GetRequiredService().ActionContext))
```
Then if you use the following extension method to create your URL's:
```c#
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:
```c#
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.
Contributor guide
Assessment
This issue has not been assessed yet.