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?
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.
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.
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.
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) ); }
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With