Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I turn a relative URL into a full URL?

Tags:

asp.net

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?

like image 414
gilles27 Avatar asked Sep 24 '08 09:09

gilles27


People also ask

Does relative hyperlink contains full URL?

The relative URL, on the other hand, does not use the full web address and only contains the location following the domain. It assumes that the link you add is on the same site and is part of the same root domain.

How do you convert relative path to absolute path?

The absolutePath function works by beginning at the starting folder and moving up one level for each "../" in the relative path. Then it concatenates the changed starting folder with the relative path to produce the equivalent absolute path.

How do you use a relative URL?

To link pages using relative URL in HTML, use the <a> tag with href attribute. Relative URL is used to add a link to a page on the website. For example, /contact, /about_team, etc.


2 Answers

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)     ); } 
like image 146
Oli Avatar answered Oct 31 '22 15:10

Oli


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(); } 
like image 38
Josh M. Avatar answered Oct 31 '22 14:10

Josh M.