How do I turn a relative URL into a full URL?
asp.netasp.net Problem Overview
This is probably explained more easily with an example. I'm trying to find a way of turning a relative URL, e.g. "/Foo.aspx" or "~/Foo.aspx" into a full URL, e.g. http://localhost/Foo.aspx. That way when I deploy to test or stage, where the domain under which the site runs is different, I will get http://test/Foo.aspx and http://stage/Foo.aspx.
Any ideas?
asp.net Solutions
Solution 1 - asp.net
Have a play with this (modified from here)
public string ConvertRelativeUrlToAbsoluteUrl(string relativeUrl) {
return string.Format("http{0}://{1}{2}",
(Request.IsSecureConnection) ? "s" : "",
Request.Url.Host,
Page.ResolveUrl(relativeUrl)
);
}
Solution 2 - asp.net
This one's been beat to death but I thought I'd post my own solution which I think is cleaner than many of the other answers.
public static string AbsoluteAction(this UrlHelper url, string actionName, string controllerName, object routeValues)
{
return url.Action(actionName, controllerName, routeValues, url.RequestContext.HttpContext.Request.Url.Scheme);
}
public static string AbsoluteContent(this UrlHelper url, string path)
{
Uri uri = new Uri(path, UriKind.RelativeOrAbsolute);
//If the URI is not already absolute, rebuild it based on the current request.
if (!uri.IsAbsoluteUri)
{
Uri requestUrl = url.RequestContext.HttpContext.Request.Url;
UriBuilder builder = new UriBuilder(requestUrl.Scheme, requestUrl.Host, requestUrl.Port);
builder.Path = VirtualPathUtility.ToAbsolute(path);
uri = builder.Uri;
}
return uri.ToString();
}
Solution 3 - asp.net
You just need to create a new URI using the page.request.url
and then get the AbsoluteUri
of that:
New System.Uri(Page.Request.Url, "Foo.aspx").AbsoluteUri
Solution 4 - asp.net
This is my helper function to do this
public string GetFullUrl(string relativeUrl) {
string root = Request.Url.GetLeftPart(UriPartial.Authority);
return root + Page.ResolveUrl("~/" + relativeUrl) ;
}
Solution 5 - asp.net
I thought I'd share my approach to doing this in ASP.NET MVC using the Uri
class and some extension magic.
public static class UrlHelperExtensions
{
public static string AbsolutePath(this UrlHelper urlHelper,
string relativePath)
{
return new Uri(urlHelper.RequestContext.HttpContext.Request.Url,
relativePath).ToString();
}
}
You can then output an absolute path using:
// gives absolute path, e.g. https://example.com/customers
Url.AbsolutePath(Url.Action("Index", "Customers"));
It looks a little ugly having the nested method calls so I prefer to further extend UrlHelper
with common action methods so that I can do:
// gives absolute path, e.g. https://example.com/customers
Url.AbsoluteAction("Index", "Customers");
or
Url.AbsoluteAction("Details", "Customers", new{id = 123});
The full extension class is as follows:
public static class UrlHelperExtensions
{
public static string AbsolutePath(this UrlHelper urlHelper,
string relativePath)
{
return new Uri(urlHelper.RequestContext.HttpContext.Request.Url,
relativePath).ToString();
}
public static string AbsoluteAction(this UrlHelper urlHelper,
string actionName,
string controllerName)
{
return AbsolutePath(urlHelper,
urlHelper.Action(actionName, controllerName));
}
public static string AbsoluteAction(this UrlHelper urlHelper,
string actionName,
string controllerName,
object routeValues)
{
return AbsolutePath(urlHelper,
urlHelper.Action(actionName,
controllerName, routeValues));
}
}
Solution 6 - asp.net
Use the .NET Uri class to combine your relative path and the hostname.
http://msdn.microsoft.com/en-us/library/system.uri.aspx
Solution 7 - asp.net
This is the helper function that I created to do the conversion.
//"~/SomeFolder/SomePage.aspx"
public static string GetFullURL(string relativePath)
{
string sRelative=Page.ResolveUrl(relativePath);
string sAbsolute=Request.Url.AbsoluteUri.Replace(Request.Url.PathAndQuery,sRelative);
return sAbsolute;
}
Solution 8 - asp.net
Simply:
url = new Uri(baseUri, url);
Solution 9 - asp.net
In ASP.NET MVC you can use the overloads of HtmlHelper
or UrlHelper
that take the protocol
or host
parameters. When either of these paramters are non-empty, the helpers generate an absolute URL. This is an extension method I'm using:
public static MvcHtmlString ActionLinkAbsolute<TViewModel>(
this HtmlHelper<TViewModel> html,
string linkText,
string actionName,
string controllerName,
object routeValues = null,
object htmlAttributes = null)
{
var request = html.ViewContext.HttpContext.Request;
var url = new UriBuilder(request.Url);
return html.ActionLink(linkText, actionName, controllerName, url.Scheme, url.Host, null, routeValues, htmlAttributes);
}
And use it from a Razor view, e.g.:
@Html.ActionLinkAbsolute("Click here", "Action", "Controller", new { id = Model.Id })
Solution 10 - asp.net
Ancient question, but I thought I'd answer it since many of the answers are incomplete.
public static string ResolveFullUrl(this System.Web.UI.Page page, string relativeUrl)
{
if (string.IsNullOrEmpty(relativeUrl))
return relativeUrl;
if (relativeUrl.StartsWith("/"))
relativeUrl = relativeUrl.Insert(0, "~");
if (!relativeUrl.StartsWith("~/"))
relativeUrl = relativeUrl.Insert(0, "~/");
return $"{page.Request.Url.Scheme}{Uri.SchemeDelimiter}{page.Request.Url.Authority}{VirtualPathUtility.ToAbsolute(relativeUrl)}";
}
This works as an extension of off Page, just like ResolveUrl and ResolveClientUrl for webforms. Feel free to convert it to a HttpResponse extension if you want or need to use it in a non-webforms environment. It correctly handles both http and https, on standard and non-standard ports, and if there is a username/password component. It also doesn't use any hard coded strings (namely ://).
Solution 11 - asp.net
Here's an approach. This doesn't care if the string is relative or absolute, but you must provide a baseUri for it to use.
/// <summary>
/// This function turns arbitrary strings containing a
/// URI into an appropriate absolute URI.
/// </summary>
/// <param name="input">A relative or absolute URI (as a string)</param>
/// <param name="baseUri">The base URI to use if the input parameter is relative.</param>
/// <returns>An absolute URI</returns>
public static Uri MakeFullUri(string input, Uri baseUri)
{
var tmp = new Uri(input, UriKind.RelativeOrAbsolute);
//if it's absolute, return that
if (tmp.IsAbsoluteUri)
{
return tmp;
}
// build relative on top of the base one instead
return new Uri(baseUri, tmp);
}
In an ASP.NET context, you could do this:
Uri baseUri = new Uri("http://yahoo.com/folder");
Uri newUri = MakeFullUri("/some/path?abcd=123", baseUri);
//
//newUri will contain http://yahoo.com/some/path?abcd=123
//
Uri newUri2 = MakeFullUri("some/path?abcd=123", baseUri);
//
//newUri2 will contain http://yahoo.com/folder/some/path?abcd=123
//
Uri newUri3 = MakeFullUri("http://google.com", baseUri);
//
//newUri3 will contain http://google.com, and baseUri is not used at all.
//
Solution 12 - asp.net
Modified from other answer for work with localhost and other ports... im using for ex. email links. You can call from any part of app, not only in a page or usercontrol, i put this in Global for not need to pass HttpContext.Current.Request as parameter
/// <summary>
/// Return full URL from virtual relative path like ~/dir/subir/file.html
/// usefull in ex. external links
/// </summary>
/// <param name="rootVirtualPath"></param>
/// <returns></returns>
public static string GetAbsoluteFullURLFromRootVirtualPath(string rootVirtualPath)
{
return string.Format("http{0}://{1}{2}{3}",
(HttpContext.Current.Request.IsSecureConnection) ? "s" : ""
, HttpContext.Current.Request.Url.Host
, (HttpContext.Current.Request.Url.IsDefaultPort) ? "" : ":" + HttpContext.Current.Request.Url.Port
, VirtualPathUtility.ToAbsolute(rootVirtualPath)
);
}
Solution 13 - asp.net
In ASP.NET MVC, you can use Url.Content(relativePath)
to convert into absolute Url