Productivity tips, reviews, tools, software and gadgets.

ResolveUrl with no Page or Control in sight
While working (sweating) on a client's website, I needed a reliable ResolveUrl method without making use of the Page or Control classes. A few quick Googles resulted in some working functions, although not all of them resulted in the same output as the real ResolveUrl.

Some solutions use the VirtualPathUtility for that, however it throws an HttpException when the url to be resolved contains a query string. The most elegant, and from what I can tell also the most correct function came from a comment by Richard Deeming on Rick Strahl's blog:

public static string ResolveUrl(string originalUrl)
if (!string.IsNullOrEmpty(originalUrl) && '~' == originalUrl[0])
int index = originalUrl.IndexOf('?');
string queryString = (-1 == index) ? null : originalUrl.Substring(index);
if (-1 != index) originalUrl = originalUrl.Substring(0, index);
originalUrl = VirtualPathUtility.ToAbsolute(originalUrl) + queryString;

return originalUrl;

To resolve the full URL, he uses the Uri and UriBuilder classes:

public static string ResolveServerUrl(string serverUrl, bool forceHttps)
Uri result = HttpContext.Current.Request.Url;
if (!string.IsNullOrEmpty(serverUrl))
serverUrl = ResolveUrl(serverUrl);
result = new Uri(result, serverUrl);
if (forceHttps && !string.Equals(result, Uri.UriSchemeHttps))
UriBuilder builder = new UriBuilder(result);
builder.Scheme = Uri.UriSchemeHttps;
builder.Port = 443;
result = builder.Uri;

return result.ToString();

This code works beautifully!

Source: read the original article and many interesting comments: ResolveUrl-without-page.

Labels: ,

  Posted by oVan on Monday, October 29, 2007 | PermaLink | 1 comments
« SuperWasp start page