In MVC 5, I had the following extension methods to generate absolute URLs, instead of relative ones:
public static class UrlHelperExtensions
{
public static string AbsoluteAction(
this UrlHelper url,
string actionName,
string controllerName,
object routeValues = null)
{
string scheme = url.RequestContext.HttpContext.Request.Url.Scheme;
return url.Action(actionName, controllerName, routeValues, scheme);
}
public static string AbsoluteContent(
this UrlHelper url,
string contentPath)
{
return new Uri(url.RequestContext.HttpContext.Request.Url, url.Content(contentPath)).ToString();
}
public static string AbsoluteRouteUrl(
this UrlHelper url,
string routeName,
object routeValues = null)
{
string scheme = url.RequestContext.HttpContext.Request.Url.Scheme;
return url.RouteUrl(routeName, routeValues, scheme);
}
}
What would the equivalent be in ASP.NET Core?
UrlHelper.RequestContext
no longer exists.- You can't get hold of the
HttpContext
as there is no longer a staticHttpContext.Current
property.
As far as I can see, you would now require the HttpContext
or HttpRequest
objects to be passed in also. Am I right? Is there some way to get hold of the current request?
Am I even on the right track, should the domain now be an environment variable, which is simple appended to the relative URL? Would this be a better approach?
For ASP.NET Core 1.0 Onwards
Bonus Tip
You can't directly register an
IUrlHelper
in the DI container. Resolving an instance ofIUrlHelper
requires you to use theIUrlHelperFactory
andIActionContextAccessor
. However, you can do the following as a shortcut:ASP.NET Core Backlog
UPDATE: This won't make ASP.NET Core 5
There are indications that you will be able to use
LinkGenerator
to create absolute URLs without the need to provide aHttpContext
(This was the biggest downside ofLinkGenerator
and whyIUrlHelper
although more complex to setup using the solution below was easier to use) See "Make it easy to configure a host/scheme for absolute URLs with LinkGenerator".