In ASP.NET MVC how can I use the Razor @Url.Content() helper from C# code?

I'm trying to write a html helper extension that outputs an image tag. I need to access (within C# code) something like Razor's @Url.Content() helper to get the proper URL for the current context. How does one do this?


Use the following to mimic Url.Content in code.

VirtualPathUtility.ToAbsolute("~/url/");

You can create your own instance of UrlHelper by passing in the appropriate ViewContext. For example, to do this from an image helper:

public static string CustomImage(this HtmlHelper html)
{
    var Url = new UrlHelper(html.ViewContext.RequestContext);
}

At this point you can call Url.Content() or any other UrlHelper method.


Something like this perhaps?

public static string MyHelper(this HtmlHelper h)
{
      string url = h.ViewContext.HttpContext.Request.Url.AbsoluteUri;
}