You can write an extension method:
public static class UrlExtensions { public static Uri GetBaseUrl(this UrlHelper url) { var uri = new Uri( url.RequestContext.HttpContext.Request.Url, url.RequestContext.HttpContext.Request.RawUrl ); var builder = new UriBuilder(uri) { Path = url.RequestContext.HttpContext.Request.ApplicationPath, Query = null, Fragment = null }; return builder.Uri; } public static string ContentAbsolute(this UrlHelper url, string contentPath) { return new Uri(GetBaseUrl(url), url.Content(contentPath)).AbsoluteUri; } }
and then suppose you have an UrlHelper instance:
string absoluteUrl = urlHelper.ContentAbsolute("~/Areas/MyUsefulApplication/Content/_awesome_template_bro/Images/MyImage.png");
If you need to do this in some other part of the code where you do not have access to the HttpContext, and create an UrlHelper, well, you should not have only the parts of your code that have access to it with URLs. Other parts of your code should not even know what the URL means.
source share