How to convert Relative URL to Absolute URL in ASP.NET page?
Copyright © 2007-2012 www.AspDotNetFaq.com
Very often we have a relative URL of some page or resource like
"~/img/logo.gif" and we need an absolute URL
to insert it in some control or link (something like
"http://www.ourserver.com/img/logo.gif")
Asp.Net 2.0 has some very useful methods that could help us to resolve the absolute URL we need.
First of them is
Page method
ResolveUrl() that converts a relative URL into one that is usable on the requesting client.
This means you we can pass to this method an URL that is relative to the current page, something like this:
Page.ResolveUrl("img/logo.gif");
and it would return to us a valid relative URL , taking into account the current URL of the Page from where you are calling it.
To explain further with an example:
(you can stay with me to get detailed explanation, or simply jump to end of the page for some useful code)
Lets imagine that we have a sub-folder called
Admin in our web application, and we have a page called
Test1.aspx
in that same sub-folder.
if we call this method from that same page - like this:
Page.ResolveUrl(
"img/logo.gif");
we would get this result:
"/Admin/img/logo.gif"
The same goes for relative URLs that start with Tilde (~) character.
They will return URLs relative to the application root.
So, by calling:
Page.ResolveUrl(
"~/Admin/Test1.aspx");
we would get:
"/Admin/Test1.aspx" which is exactly what we need!
Also, Relative URLs that climb up through the folder tree (
"../") are perfectly valid - if they do not break
out of application root. (Be careful, you will get an Exception if you try to climb too high!)
Again, if we go back to that page at
/Admin/Test1.aspx and call ResolveUrl like this:
Page.ResolveUrl(
"~/Admin/Test2.aspx");
we would get: "
/AdminTest2.aspx".
Now we are getting somewhere - we are much closer to the point where we can construct
valid Absolute URL for any relative URL.
We will have to use the
Request.Url property (
HttpRequest.Url) that
returns information about the URL of the current request,
and extract its
Host property to get the name of the server we are currently running on.
Also we will need to check if the current request is running over
SSL in order to decide if we will use HTTP or HTTP
as a prefix to our Absolute URL.
So finally here it is, method that constructs valid Absolute URL from any valid Relative URL:
public string ConvertRelativeUrlToAbsoluteUrl(string relativeUrl)
{
if (Request.IsSecureConnection)
return string.Format("https://{0}{1}", Request.Url.Host, Page.ResolveUrl(relativeUrl));
else
return string.Format("http://{0}{1}", Request.Url.Host, Page.ResolveUrl(relativeUrl));
}
Thanks to
George Henry for his corrections to this FAQ.
Copyright © 2007-2012 www.AspDotNetFaq.com