ASP.NET 中设置路径的三种方式

 

下面列举的是ASP.NET 开发中,常用的设置路径的三种方式。

 

Default.aspx.cs 代码如下:

public partial class _Default : System.Web.UI.Page 
{ 
 public string GetUrl(string _img)
 {
 //获取服务器上 ASP.NET 应用程序的虚拟应用程序根路径。
 string root = Request.ApplicationPath;
 
 //返回图片根目录下的绝对路径,并添加双引号。
 return '"'+ root + "/img/" + _img +'"';
 }
 protected void Page_Load(object sender, EventArgs e)
 { }
}

 

Default.aspx 代码如下:

<body>
 <form id="form1" runat="server">
 
 <img src="/三种地址的指定方式/img/book1.jpg" alt="HTML标签"/>
 
 <asp:Image runat="server" ImageUrl="~/img/book2.jpg" AlternateText="服务器控件的Alt属性"/>
 
 <img src=<%=GetUrl("book3.jpg")%> alt="从.cs 代码获得路径"/> 
 <!-- <%=GetUrl("book3.jpg");%> 这种方式错误!调用的函数后面不要添加“;”分号。-->
 </form>
</body>

注意:“/三种地址的指定方式”是这个站点的 根目录文件夹 的名字(根目录从根文件夹开始)。

 

运行的后,“查看源文件”的代码如下:

<body>
 <form name="form1" method="post" action="Default.aspx" id="form2">
<div>
 <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE"  
 value="/wEPDwULLTEwMTM4Mzg2MDJkZBus1frYuS31/0rZBi7gTRQlSein" />
</div>
 <img src="/三种地址的指定方式/img/book1.jpg" alt="HTML标签"/>
 
 <img src="img/book2.jpg" alt="服务器控件的Alt属性" style="border-0px;" />
 
 <img src="/三种地址的指定方式/img/book3.jpg" alt="从.cs 代码获得路径"/>
 
 </form>
</body>

 

总结:

○ 使用 <img /> 这种HTML 标签的方式是最简单的;

○ 使用 <asp: /> 服务器控件的方式是最安全的;

○ 使用后台代码加 <%=  %> 的方式是最灵活的(注意:调用的函数后面不要添加“;”分号);

 

如何获得站点虚拟路径所对应的磁盘物理路径

string path = Server.MapPath("img");
Response.Write(path);
// 打印结果: C:\Web_Test\三种地址的指定方式\img 

 

附加:Request获取url信息的各种方法


在ASP.NET 编程中,经常需要用Request 获取url 的有关信息,Request 中有多种方法获取url 信息,下面将各种方法得到的结果列出来。

测试的url 地址是 http://www.test.com/testweb/default.aspx, 结果如下:

Request.ApplicationPath:  /testweb
Request.CurrentExecutionFilePath:  /testweb/default.aspx
Request.FilePath:  /testweb/default.aspx
Request.Path:  /testweb/default.aspx
Request.PathInfo:
Request.PhysicalApplicationPath:  E:\WWW\testweb\
Request.PhysicalPath:  E:\WWW\testweb\default.aspx
Request.RawUrl:  /testweb/default.aspx
Request.Url.AbsolutePath:  /testweb/default.aspx
Request.Url.AbsoluteUri:  http://www.test.com/testweb/default.aspx
Request.Url.Host:  www.test.com
Request.Url.LocalPath:  /testweb/default.aspx

作者: XuGang   网名:钢钢
出处: http://xugang.cnblogs.com
声明: 本文版权归作者和博客园共有。转载时必须保留此段声明,且在文章页面明显位置给出原文连接地址!
原文地址:https://www.cnblogs.com/xugang/p/1880657.html