Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relative and absolute paths on ASP.NET/IIS

Tags:

path

asp.net

iis

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?

like image 887
notAnonymousAnymore Avatar asked Oct 06 '11 12:10

notAnonymousAnymore


3 Answers

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>
like image 84
KV Prajapati Avatar answered Sep 28 '22 01:09

KV Prajapati


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>
like image 38
rick schott Avatar answered Sep 28 '22 02:09

rick schott


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 givenhttp://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.

like image 23
Simon Halsey Avatar answered Sep 28 '22 02:09

Simon Halsey