19 December 2010

Resolving an App-Relative URL without a Page Object Reference

If you’ve worked with ASP.NET before then you’ve almost certainly seen an application-relative URL like ~/SomeFolder/SomePage.aspx.  The tilde at the beginning is a stand in for the application path, and it can easily be resolved using the Page object’s ResolveUrl method:

string url = Page.ResolveUrl(“~/SomeFolder/SomePage.aspx”);

There are times, however, when you don’t have a page object available and you need to resolve an application relative URL.  Assuming you have an HttpContext object available, the following method will accomplish just that:

public static string ResolveAppRelativeUrl(string url)
     return url.Replace(“~”, System.Web.HttpContext.Current.Request.ApplicationPath);

It just replaces the tilde with the application path, which is essentially all the ResolveUrl method does.

For more articles like this, sign up to the fortnightly Simple-Talk newsletter.


  • Rate
    [Total: 0    Average: 0/5]

Damon Armstrong is a Senior Engineering Team Lead with GimmalSoft in Dallas, Texas, and author of Pro ASP.NET 2.0 Website Programming. He specializes in Microsoft technologies with a focus on SharePoint and ASP.NET. When not staying up all night coding, he can be found playing disc golf, softball, working on something for Carrollton Young Life, or recovering from staying up all night coding.

View all articles by Damon Armstrong