我想完全理解如何在静态和动态文件中使用相对和绝对 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\images\gif\arrow.png",这在客户端意义不大,
您应该将其用于正确的客户端相对路径:
aspxImgCtrl.ImageUrl = "~/Images/GIF/arrow.png";
要从 javascript 引用资源,您可能需要考虑使用一级文件夹结构来统一访问路径。例如:
- 页面
- JS
- 像素
- 等...
有关更多详细信息,请访问 asp.net web site paths
关于asp.net - 获取网站根目录的基本 url(绝对/相对 url),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2540021/