I thought I shared my approach to 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(); } }
Then you can infer the absolute path using:
// gives absolute path, eg https://example.com/customers Url.AbsolutePath(Url.Action("Index", "Customers"));
It looks a little ugly having nested method calls, so I prefer to extend UrlHelper with common action methods so that I can:
// gives absolute path, eg 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)); } }
stucampbell Jan 21 '13 at 14:06 2013-01-21 14:06
source share