Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC - absolute URL to content to be determines from outside controller or view

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).

like image 664
Nippysaurus Avatar asked Dec 28 '22 14:12

Nippysaurus


1 Answers

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.

like image 159
Darin Dimitrov Avatar answered Jan 30 '23 20:01

Darin Dimitrov