I thought I'd share my approach to doing this in ASP.NET MVC using the Uri
class and some extension magic.
public static class UrlHelperExtensions
{
public static string AbsolutePath(this UrlHelper urlHelper,
string relativePath)
{
return new Uri(urlHelper.RequestContext.HttpContext.Request.Url,
relativePath).ToString();
}
}
You can then output an absolute path using:
// gives absolute path, e.g. https://example.com/customers
Url.AbsolutePath(Url.Action("Index", "Customers"));
It looks a little ugly having the nested method calls so I prefer to further extend UrlHelper
with common action methods so that I can do:
// gives absolute path, e.g. https://example.com/customers
Url.AbsoluteAction("Index", "Customers");
or
Url.AbsoluteAction("Details", "Customers", new{id = 123});
The full extension class is as follows:
public static class UrlHelperExtensions
{
public static string AbsolutePath(this UrlHelper urlHelper,
string relativePath)
{
return new Uri(urlHelper.RequestContext.HttpContext.Request.Url,
relativePath).ToString();
}
public static string AbsoluteAction(this UrlHelper urlHelper,
string actionName,
string controllerName)
{
return AbsolutePath(urlHelper,
urlHelper.Action(actionName, controllerName));
}
public static string AbsoluteAction(this UrlHelper urlHelper,
string actionName,
string controllerName,
object routeValues)
{
return AbsolutePath(urlHelper,
urlHelper.Action(actionName,
controllerName, routeValues));
}
}