ResolveUrl Method outside of a Page or Control, or in a Static method
This is an update to my original post on this topic:
Nathan offered this alternative to my original utility function posted here:
VirtualPathUtility.ToAppRelative("~/path/to/item");
Now the original post follows:
Sometimes we create Utility classes or Functions that provide path related functionality, and finding or resolving a path relative to the current request may be necessary. In an ASP.NET Page or Control, the ResolveUrl function is available for this. But if you need this functionality in a class in App_Code, for example, it gets a little tricky. The System.Web.VirtualPathUtility class methods could be used to achieve ResolveUrl like functionality, but there is an easier way. You could always get a reference to the current (executing) ASP.NET Page by casting Context.Handler to Page, and then call ResolveUrl on the Page. This should work in most situations because the only time you would need to Resolve Url is when you are running in the context of a Page. So the code would look like the following:
public static string ResolveUrl(string relativeUrl)
{
if (HttpContext.Current != null)
{
System.Web.UI.Page p = HttpContext.Current.Handler as System.Web.UI.Page;
if (p != null)
return p.ResolveUrl(relativeUrl);
else
throw new InvalidOperationException("Unable to Resolve: Not in a Page Context");
}
else
throw new InvalidOperationException("Unable to Resolve: Not in a HttpContext");
}
Once you obtain a reference to the current Page via Context.Handler, you can pretty much do everything you could do within a Page.
Posted on August 20, 2008 05:19 by
Haider