我使用asp.net 4和c#。
我有这个代码,可以让我找到一个图像的物理路径。正如你所看到的,我得到了我的机器物理页面file:///C:.
string pathRaw = HttpContext.Current.Request.PhysicalApplicationPath + "Statics\Cms\Front-End\Images\Raw\";
结果:
file:///C:/......../f005aba1-e286-4d9e-b9db-e6239f636e63.jpg
但是我需要在我的web应用程序的前端显示这个图像,所以我需要这样的结果:
http://localhost:1108/Statics/Cms/Front-End/Images/Raw/f005aba1-e286-4d9e-b9db-e6239f636e63.jpg
怎么做?
PS:我需要转换变量pathRaw的结果。
希望我能表达自己,不幸的是,我不确定这种情况下的术语。
谢谢你的帮助!
最简单的方法就是去掉物理应用程序路径。如果在代码中无法做到这一点,只需将其从pathRaw变量中删除即可。像这样:
public string GetVirtualPath( string physicalPath )
{
if ( !physicalPath.StartsWith( HttpContext.Current.Request.PhysicalApplicationPath ) )
{
throw new InvalidOperationException( "Physical path is not within the application root" );
}
return "~/" + physicalPath.Substring( HttpContext.Current.Request.PhysicalApplicationPath.Length )
.Replace( "\", "/" );
}
代码首先检查路径是否在应用程序根目录中。如果没有,则无法确定文件的url,因此会引发异常。
虚拟路径是通过剥离物理应用程序路径来构建的,将所有反斜杠转换为斜杠,并在路径前面加上"~/"
,以表明它应该被解释为相对于应用程序根。
之后,您可以使用ResolveClientUrl(virtualPath)将虚拟路径转换为相对路径,以输出到浏览器。
使用Request.ApplicationPath获取应用程序的根然后使用这个问题的答案来获得相对路径。
它可能需要一些调整,但它应该允许你做你想要的事情。
通过Request.ApplicationPath左剥离您的pathRaw内容,并使用构建url
Uri navigateUri = new Uri(System.Web.HttpContext.Current.Request.Url, relativeDocumentPath);
利用ApplicationPath
-获取服务器上ASP.NET应用程序的虚拟应用程序根路径。
Label1.Text = Request.ApplicationPath;
Image1.ImageUrl = Request.ApplicationPath + "/images/Image1.gif";
您可以使用Server.MapPath进行此操作。
string pathRaw = System.Web.HttpContext.Current.Server.MapPath(“somefile.jpg“);