Programmatically resolving ~ URL's to the Virtual Root using ResolveURL()

It's common knowledge that a control, when Runat="server" will resolve it's src or href attribute to a virtual root when the URL starts with ~/

For example:

<a href="~/Customers/Profile.aspx" Runat="server">Profile</a>

will become:

<a href="" Runat="server">Profile</a>

How do we do this programmatically?

The base WebControl class exposes a method named ResolveURL(). This method accepts a url such as "~/Customers/Profile.aspx" and returns the real url, starting from your site's virtual root.

To get to this functionality you can use the following pattern:

string url = Page.ResolveClientUrl("~/Customers/Profile.aspx");


string url = VirtualPathUtility.ToAbsolute("~/Customers/Profile.aspx");


Image x = new Image();
string url = x.ResolveUrl("~/Customers/Profile.aspx");
Author Paul Hayman

Paul is the COO of kwiboo ltd and has more than 20 years IT consultancy experience. He has consulted for a number of blue chip companies and has been exposed to the folowing sectors: Utilities, Telecommunications, Insurance, Media, Investment Banking, Leisure, Legal, CRM, Pharmaceuticals, Interactive Gaming, Mobile Communications, Online Services.

Paul is the COO and co-founder of kwiboo ( and is also the creator of GeekZilla.


Anonymous said:

Excellent article.... Really helped me out

12/Jul/2006 15:33 PM

Vladek said:

Yes, it's very handy method.

Well, here is a method to resolve URLs for HTML tags, which are not or cannot be marked with runat="server":

<a href="<%= ResolveUrl("~/Customers/Profile.aspx") %>">Profile</a>

Just use <%=%> to place small pieces of code into HTML.

19/Jun/2007 12:17 PM


JIT information. Great work, and thanks!

11/Oct/2007 17:16 PM

Me said:

It does not add the server, the output is more like

<a href="/site/Customers/Profile.aspx" Runat="server">Profile</a>

14/Feb/2008 16:43 PM

Jack said:

Thanks for your tip on the VirtualPathUtility. I had to implement something like this for a WebService, but I needed the full url to the root. Here's my C# code:

string path = VirtualPathUtility.ToAbsolute("~/setup.msi");

// this should return the end portion of the url (ie: /test/setup.msi)

// so we should be able to use this to find our actual url:

string baseurl = Context.Request.Url.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped);

string url = Config.UriCombine(baseurl, path);

return url;

The helper method UriCombine (like Path.Combine):

public static string UriCombine(string str, params string[] param)


    string b = str;

    for (int i = 0; i < param.Length; i++)


        if (!b.EndsWith("/"))


            b = b + "/";


        Uri uri = new Uri(b);

        b = new Uri(uri, param[i]).AbsoluteUri;


    return new Uri(b).AbsoluteUri;


01/Jan/2011 08:24 AM

Add Comment


Your comment has been received and will be shown once it passes moderation.