I have some content which is sitting in a path something like this:
/Areas/MyUsefulApplication/Content/_awesome_template_bro/Images/MyImage.png
Is there a way get a fully qualified absolute URL to that path without being in a controller or view (where url helpers are readily available).
You could 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 assuming you have an instance of UrlHelper:
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 don't have access to an HttpContext and build an UrlHelper, well, you shouldn't as only parts of your code that have access to it should deal with urls. Other parts of your code shouldn't even know whan an url means.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With