I've read many articles about relative/absolute paths, but I still can't grok this problem.
The following code is from my ASP.NET Master
page:
<li><a>Reports</a>
<ul>
<li>
<a href="/Reports/One.aspx">One</a>
</li>
<li>
<a href="~/Reports/Two.aspx">Two</a>
</li>
</ul>
</li>
(Note that one link has a ~
and one doesn't.)
When running the site, the first link points to http://server/Reports/One.aspx
, and the second link points to http://server/company/project/Reports/~/Reports/Two.aspx
.
How do I get to the root of my ASP.NET project without it ignoring whatever virtual directories are set up on IIS?
Add runat="server"
attribute to the anchor tag. You can't use the ~ root operator with HTML tags. Only the server controls (Html or Web) can use it.
<a runat="server" href="~/Reports/Two.aspx">Two</a>
Use Page.ResovleUrl
for all of your files if you don't want them to be server controls with generated Ids:
<a href='<%= Page.ResolveUrl("~/Reports/Two.aspx")%>'>Two</a>
A relative path is relative to the current resource, so if you were viewing
http://yourhost/app/default.aspx
a relative path of reports/one.aspx
would be http://yourhost/app/reports/one.aspx
. Note the absence of a leading /
in the relative path. That's what makes it relative.
An absolute path, as you can probably guess, starts with a /
, and it uses the hostname of the current resource, so that would http://yourhost/reports/one.aspx
.
~ is an red herring. It's a .NET-only addition used by various parts of ASP.NET to base your path off the current application root. So if your application root was http://yourhost/app
, you were viewing http://yourhost/app/views/default.aspx
, and you asked .NET for the path ~/reports/one.aspx', you would be given
http://yourhost/app/reports/one.aspx`.
~ isn't used by HTML, IIS or URLs, so if your browser sees it, it'll just use it as is.
Note: Some Unix servers can use ~
to map in a user's home directory, but that's just complicating things.
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