ASP.NET: Use Url.Content() from Razor to Resolve Relative URLs

You often need to resolve a relative URL to the proper absolute URL when using server-side programming platforms. Differences between development, test and production environments often mean the web server configuration for the application changes from one environment to another. Linking to resources can become nightmarish when moving from a virtual directory in dev to a website root in test to yet another application directory in prod.

The handy-dandy Url.Content() method in the System.Web.Mvc.UrlHelper class allows you to easily convert a virtual-root relative path (you know, the one that begins with a tilde (~) character) to an application absolute path. This works great in MVC Razor projects and the Razor view engine makes it a snap to pop the method into an href for an anchor element.

[sourcecode language=”html”]

<p>This link goes to my <a href="@Url.Content("~/")">Application home page</a>.</p>
<p>Now let’s link to a view <a href="@Url.Content("~/Controller/Action")">in the Controller/Action directory</a>.

You can use this technique with images and other resources, too. Just remember to put the original link content in virtual root-relative form (~/MyResource/Path) and pass it to the Url.Content() method!

1 Comment

  1. craig

    Thanks. It was right to the point.

Sign in
Forgot password?
Sign up

(*) Required fields

I agree with OptimaSales Terms & Privacy Policy