我正在尝试使用 System.Web.VirtualPathUtility.ToAbsolute() 将相对路径转换为绝对路径
但是我得到了这个错误:
此处不允许使用相对虚拟路径'./images/gift-card.jpg'。
对了,文件结构是
此代码位于 .cs 文件中,并且此文件与其他 .aspx 文件位于同一文件夹(假设为/root)中。图片在文件夹/root/images/
有什么想法吗?
附言: 即使我将路径更改为“~/images/gift-card.jpg”,它仍然会引发异常:未处理的异常,没有更多信息。
请您参考如下方法:
VirtualPathUtility.ToAbsolute() 是一个静态函数,它不知道任何本地 cotnext,例如当前请求的目录。
因此,你不能给它传递一个相对路径。
相反,您必须向它传递一个绝对应用程序相对路径,以 ~/ 开头。
参见documentation中的备注:
An application absolute path is one where the application path is used instead of the root operator (the tilde [~]).
If virtualPath is:
Absolute, the ToAbsolute method returns the virtual path unchanged.
Application relative, the ToAbsolute method appends the current application virtual directory path to the beginning of the virtualPath. For example, the current application virtual directory path can be accessed from the AppDomainAppVirtualPath property.
Not rooted, the ToAbsolute method raises an ArgumentOutOfRangeException exception.
