Created
June 3, 2020 14:09
-
-
Save stefankip/7b12254692991be48c88547194b1f0b6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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