Created
March 7, 2012 18:32
-
-
Save jchadwick/1994976 to your computer and use it in GitHub Desktop.
External URL Helpers
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
using System; | |
using System.Web; | |
using System.Web.Mvc; | |
public static class UrlExtensions | |
{ | |
public static string ExternalAction(this UrlHelper url, string actionName, string controllerName, object routeValues = null) | |
{ | |
var requestUrl = url.Action(actionName, controllerName, routeValues); | |
return ExternalUrl(url, requestUrl); | |
} | |
public static string ExternalUrl(this UrlHelper url, string relativeUrl) | |
{ | |
return ExternalUrl(url.RequestContext.HttpContext.Request, relativeUrl); | |
} | |
public static string ExternalUrl(this HtmlHelper html, string relativeUrl) | |
{ | |
return ExternalUrl(html.ViewContext.HttpContext.Request, relativeUrl); | |
} | |
public static string ExternalUrl(this HttpRequestBase request, string relativeUrl) | |
{ | |
return UrlHelpers.ExternalUrl(request.Url, relativeUrl); | |
} | |
} |
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
using System; | |
using System.Web; | |
public static class UrlHelpers | |
{ | |
public static string ExternalUrl(string requestUrl, string relativeUrl, bool forcePort80 = false) | |
{ | |
return ExternalUrl(new Uri(requestUrl), relativeUrl, forcePort80); | |
} | |
public static string ExternalUrl(Uri requestUrl, string relativeUrl, bool forcePort80 = false) | |
{ | |
var absoluteUrl = relativeUrl; | |
if(relativeUrl.StartsWith("~/")) | |
absoluteUrl = VirtualPathUtility.ToAbsolute(relativeUrl); | |
var hostPath = new UriBuilder | |
{ | |
Host = requestUrl.Host, | |
Path = "/", | |
Port = requestUrl.Port, | |
Scheme = requestUrl.Scheme, | |
}; | |
if(forcePort80) | |
hostPath.Port = 80; | |
return new Uri(hostPath.Uri, absoluteUrl).AbsoluteUri; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment