Thursday, December 4, 2008

ASP.NET Convert a Relative URL to an Absolute URL

My ASP.NET web application needed to send a notification e-mail to a user that included a dynamically generated link. To create this link, I wanted to pass a relative url including the tilde i.e ("~/DirectoryA/Webform.aspx?querystring=1") and have an absolute url returned ("http://www.domain.com/DirectoryA/Webform.aspx?querystring=1")

So I wrote this:

public string ResolveAbsoluteUrl(string url)
{
// Get the site root
string rawURL = Request.Url.ToString();

// Find the end of the root
int rootEnd = rawURL.IndexOf('/', rawURL.IndexOf("//") + 2);
if (rootEnd < 0) { rootEnd = rawURL.Length; }

// Combine the root with the resolved url
string rootURL = rawURL.Substring(0, rootEnd);

return string.Format("{0}{1}", rootURL, ResolveUrl(url));
}

No comments: