tags:

views:

1323

answers:

5

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?

A: 

Request.Url.Host

kitsune
+8  A: 

Have a play with this (modified from here)

public string ConvertRelativeUrlToAbsoluteUrl(string relativeUrl) {
    if (Request.IsSecureConnection)
        return string.Format("https://{0}{1}", Request.Url.Host, Page.ResolveUrl(relativeUrl));

    return string.Format("http://{0}{1}", Request.Url.Host, Page.ResolveUrl(relativeUrl));
}
Oli
I was hoping there was something built-in to ASP .NET so I don't have to get into all the business of looking at protocols, ports, etc but this should do the job.
gilles27
Just a note: When I used this I added Request.URL.Port between the host and page url so it would work on the Visual Web Dev testing server.
amdfan
A: 

Use the .NET Uri class to combine your relative path and the hostname.
http://msdn.microsoft.com/en-us/library/system.uri.aspx

+3  A: 

The by far easiest way is to use the class VirtualPathUtility and its method ToAbsolute:

string absolutePath = VirtualPathUtility.ToAbsolute(appRelativePath);
Seb Nilsson
Will this return a full URL with the host, e.g. http://localhost, at the start? I can't seem to get it to work that way,
gilles27
-1 This method is a lie, this is more of "ToAbsoluteClientUrl" not actually an absolute Url
Chris Marisic
A: 

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) ;
}
StocksR