我使用 asp.net 4 和 c#。
我有这段代码可以让我找到图像的物理路径。 如您所见,我得到了我的机器物理 pagh 文件:///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) 将虚拟路径转换为相对路径以输出到浏览器.
关于c# - 将物理路径转换为关于 http ://localhost: 的相对路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6276978/