Get Absolute URL from Relative path (refactored method) Get Absolute URL from Relative path (refactored method) asp.net asp.net

Get Absolute URL from Relative path (refactored method)


This has always been my approach to this little nuisance. Note the use of VirtualPathUtility.ToAbsolute(relativeUrl) allows the method to be declared as an extension in a static class.

/// <summary>/// Converts the provided app-relative path into an absolute Url containing the /// full host name/// </summary>/// <param name="relativeUrl">App-Relative path</param>/// <returns>Provided relativeUrl parameter as fully qualified Url</returns>/// <example>~/path/to/foo to http://www.web.com/path/to/foo</example>public static string ToAbsoluteUrl(this string relativeUrl) {    if (string.IsNullOrEmpty(relativeUrl))        return relativeUrl;    if (HttpContext.Current == null)        return relativeUrl;    if (relativeUrl.StartsWith("/"))        relativeUrl = relativeUrl.Insert(0, "~");    if (!relativeUrl.StartsWith("~/"))        relativeUrl = relativeUrl.Insert(0, "~/");    var url = HttpContext.Current.Request.Url;    var port = url.Port != 80 ? (":" + url.Port) : String.Empty;    return String.Format("{0}://{1}{2}{3}",        url.Scheme, url.Host, port, VirtualPathUtility.ToAbsolute(relativeUrl));}


new System.Uri(Page.Request.Url, "/myRelativeUrl.aspx").AbsoluteUri


This one works for me...

new System.Uri(Page.Request.Url, ResolveClientUrl("~/mypage.aspx")).AbsoluteUri