ASP.NET MVC - The absolute URL for content to be determined from an external controller or viewer

I have content that sits on the go something like this:

/Areas/MyUsefulApplication/Content/_awesome_template_bro/Images/MyImage.png

Is there a way to get the full absolute URL of this path without being in the controller or view (where the URL helpers are available).

+4
source share
2 answers

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.

+9
source

The main question, of course, is where would you like to get the URL if not in the controller or in the view? What other places exist in an ASP.NET MVC application?

If you are involved in other tiers of applications that are not familiar with the web interface, then this will be a bit complicated. These applications (assemblies) can have a custom configuration where you can put the root directory of the web application, and they can use it. but you have to change it for production.

Or add the System.Web link to another application and get access to the current HttpContext when Darin showed you what is an even more pleasant solution.

+1
source

All Articles