Skip to content

Instantly share code, notes, and snippets.

@sebnilsson
Last active September 27, 2015 13:17
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 sebnilsson/1275714 to your computer and use it in GitHub Desktop.
Save sebnilsson/1275714 to your computer and use it in GitHub Desktop.
UrlHelper.ToAbsolute
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