Wednesday, October 6, 2010

ASP.NET - Convert Relative URL to Absolute (Part 2)

This is a follow up to my previous post: ASP.NET - Convert Relative URL to Absolute.

Twitter user @GeertDoornbos alerted me to a more concise way to convert a relative URL to an absolute which offers the same conversion functionality, but works with file-system relative paths (/path/to/foo or ../path/to/foo) instead of app-relative paths (~/path/to/foo). Check it out:

public static string ToAbsoluteUrl(this string relativeUrl) {
    if(HttpContext.Current == null || string.IsNullOrEmpty(relativeUrl)) 
        return relativeUrl;
    
    return new Uri(HttpContext.Current.Request.Url, relativeUrl).ToString();
}

It should be noted that my technique and this one are not interchangable because app-relative paths have a different meaning to the Uri object than file system relative paths. Namely, if the current Request.Url were equal to 'http://www.website.com/foo/bar' and I passed the Uri constructor `~/path/to/file` it would interpret the path as 'http://www.website.com/foo/bar/~/path/to/file` instead of 'http://www.website.com/path/to/file`.

Thanks again for the tip @GeertDoornbos.