获取网站根目录的基本URL(绝对/相对URL)

7

我希望能够完全理解在静态和动态文件中如何使用相对和绝对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地址?

1个回答

7

仅当使用服务器控件和服务器代码时,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引用资源,您可以考虑使用一级文件夹结构来统一访问路径。例如:

  • Pages(页面)
  • JS(脚本)
  • Pix(图片)
  • 等等...

有关更多详细信息,请访问asp.net网站路径


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接