Skip to content

Instantly share code, notes, and snippets.

@stefankip
Created June 3, 2020 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stefankip/7b12254692991be48c88547194b1f0b6 to your computer and use it in GitHub Desktop.
Save stefankip/7b12254692991be48c88547194b1f0b6 to your computer and use it in GitHub Desktop.
public static class StringExtensions
{
/// <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) || relativeUrl.StartsWith("http"))
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 $"{url.Scheme}://{url.Host}{port}{VirtualPathUtility.ToAbsolute(relativeUrl)}";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment