简体   繁体   中英

Relative and absolute paths on 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?

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>

如果您不希望它们成为具有生成的ID的服务器控件,请将Page.ResovleUrl用于所有文件:

<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.

Please read There is something about "Paths" for ASP.NET beginners . It will give a complete idea on "Paths" in an ASP.NET application.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM