Last active
September 27, 2015 13:17
-
-
Save sebnilsson/1275714 to your computer and use it in GitHub Desktop.
UrlHelper.ToAbsolute
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 string ToAbsolute(this UrlHelper urlHelper, string appRelativeUrl, | |
string relativeHostName = null, bool? useSecureConnection = null) { | |
var httpContext = urlHelper.RequestContext.HttpContext; | |
if(string.IsNullOrWhiteSpace(relativeHostName) && httpContext.Request == null) { | |
throw new ArgumentException("The provided host-name cannot be null or empty if there is no current HttpContext.", "relativeHostName"); | |
} | |
relativeHostName = (relativeHostName ?? string.Empty).Trim(new[] { '/' }); | |
if(!Uri.IsWellFormedUriString(relativeHostName, UriKind.Relative)) { | |
throw new ArgumentException("The provided host-name must be a well-formed relative URI.", "relativeHostName"); | |
} | |
bool isSecure = (useSecureConnection.HasValue) ? useSecureConnection.Value | |
: ((httpContext != null) ? httpContext.Request.IsSecureConnection : false); | |
string protocol = isSecure ? "https://" : "http://"; | |
string domain = (!string.IsNullOrWhiteSpace(relativeHostName)) | |
? relativeHostName : httpContext.Request.Url.Host; | |
string relativeUrl = urlHelper.Content(appRelativeUrl); | |
string absoluteUrl = string.Format("{0}{1}/{2}", protocol, domain, relativeUrl); | |
return absoluteUrl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment