获取网站根目录的基址(绝对/相对url)
问题描述:
我想完全理解如何在静态和动态文件中使用相对和绝对url地址。获取网站根目录的基址(绝对/相对url)
~ :
/:
.. : in a relative URL indicates the parent directory
. : refers to the current directory
/: always replaces the entire pathname of the base URL
// : always replaces everything from the hostname onwards
这个例子很容易在没有虚拟目录的情况下工作。但我正在处理虚拟目录。
Relative URI Absolute URI
about.html http://WebReference.com/html/about.html
tutorial1/ http://WebReference.com/html/tutorial1/
tutorial1/2.html http://WebReference.com/html/tutorial1/2.html
/ http://WebReference.com/
//www.internet.com/ http://www.internet.com/
/experts/ http://WebReference.com/experts/
../ http://WebReference.com/
../experts/ http://WebReference.com/experts/
../../../ http://WebReference.com/
./ http://WebReference.com/html/
./about.html http://WebReference.com/html/about.html
我想模拟下面的网站,就像我的项目正在虚拟目录中工作。
这些都是我的aspx和ascx的文件夹
http://hostAddress:port/virtualDirectory/MainSite/ASPX/default.aspx
http://hostAddress:port/virtualDirectory/MainSite/ASCX/UserCtrl/login.ascx
http://hostAddress:port/virtualDirectory/AdminSite/ASPX/ASCX/default.aspx
这些是我的JS文件(将与ASPX和ASCX文件中同时使用):
http://hostAddress:port/virtualDirectory/MainSite/JavascriptFolder/jsFile.js
http://hostAddress:port/virtualDirectory/AdminSite/JavascriptFolder/jsFile.js
这是我的静态网页地址(我想显示一些图片并运行一些js功能):
http://hostAddress:port/virtualDirectory/HTMLFiles/page.html
这是我的图像折叠呃
http://hostAddress:port/virtualDirectory/Images/PNG/arrow.png
http://hostAddress:port/virtualDirectory/Images/GIF/arrow.png
如果我想要写和图像文件在我的ASPX文件链接我应该写
aspxImgCtrl.ImageUrl = Server.MapPath("~")+"/Images/GIF/arrow.png";
但是如果我想要写硬编码或从JavaScript文件的路径,什么样的url地址应该是?
答
〜运算符仅在服务器控件和服务器代码中被asp.net识别。您不能对客户端元素使用〜运算符。在服务器控制
绝对和相对路径引用有以下缺点:
•绝对路径不是应用程序之间进行移植。如果您移动绝对路径指向的应用程序,则链接将中断。
•如果将资源或页面移至不同文件夹,客户端元素样式中的相对路径可能难以维护。
为了克服这些缺点,ASP.NET包含Web应用程序根操作符(〜),您可以在服务器控件中指定路径时使用它。 ASP.NET将〜运算符解析为当前应用程序的根目录。您可以将〜操作符与文件夹结合使用来指定基于当前根目录的路径。
至于例如你贴
aspxImgCtrl.ImageUrl = Server.MapPath("~")+"/Images/GIF/arrow.png";
上述代码将使服务器物理路径(例如 - C:\的Inetpub \ wwwroot的\ mysite的\图像\ GIF \ arrow.png”,其意思少在客户端,
,你应该用这个正确的客户端的相对路径:
aspxImgCtrl.ImageUrl = "~/Images/GIF/arrow.png";
要引用JavaScript中,你可能要考虑一个水平folde资源rs结构来统一访问路径。例如:
- 页面
- JS
- Pix的
- 等...
欲了解更多详情,请访问asp.net web site paths