Relative and absolute paths on ASP.NET/IIS

二次信任 提交于 2020-01-02 04:41:09

问题


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?


回答1:


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>



回答2:


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>



回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/7674117/relative-and-absolute-paths-on-asp-net-iis

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!