我想使用 VirtualPathUtility.ToAbsolute $解决应用程序相对路径,如〜/ MyPage.aspx
,应用绝对路径,如 /MySite/MyApp/MyPage.aspx
。然而,一些路径,我收到一封 HttpException
说我的路径是不是有效的虚拟路径。例如:
I'm trying to use VirtualPathUtility.ToAbsolute
to resolve app-relative paths, such as ~/MyPage.aspx
, to application-absolute paths, such as /MySite/MyApp/MyPage.aspx
. However, with some paths, I receive an HttpException
saying that my path is "not a valid virtual path". Examples:
// This works:
var abs1 = VirtualPathUtility.ToAbsolute("~/MyPage.aspx#anchor");
// This errors:
var abs2 = VirtualPathUtility.ToAbsolute("~/MyPage.aspx?key=value");
这是怎么回事?
What's going on?
由于您使用的是.NET 3.5,您使用的是 2.0
的System.Web
组件,它有一个?被认为是由该方法非法路径字符。这是中提到的特定版本的MSDN页面
Because you're using .NET 3.5, you're using the 2.0
System.Web
assembly, which has the defect that ?
is considered an illegal path character by this method. This is mentioned in the community comments on the version-specific MSDN page.
通过拆卸,可以看出,呼叫终止于(内部
) VirtualPath.Create
,其中有:
By disassembling, it can be seen that the call ends up in the (internal
) VirtualPath.Create
, which has:
else if (VirtualPath.ContainsIllegalVirtualPathChars(virtualPath))
{
throw new HttpException(System.Web.SR.GetString("Invalid_vpath", new object[1]
{
(object) virtualPath
}));
}
该引用
private static char[] s_illegalVirtualPathChars = new char[4]
{
':',
'?',
'*',
char.MinValue
};
有些可以合理地认为是坏字符的路径,但?
真不该这么拒绝了。
Some of these can reasonably be regarded as bad characters for a path, but ?
shouldn't really be so rejected.
的 4.0
的System.Web
显示反汇编 VirtualPath.Create
已被重写,更加挑剔。
Disassembly of the 4.0
System.Web
shows that VirtualPath.Create
has been rewritten to be more discerning.
This一个现在已不存在blogs.msdn帖子的web.archive截图显示的最早提到这个问题。在MS员工响应:
This web.archive capture of a now-defunct blogs.msdn post shows one of the earliest mentions of this problem. The MS employee responds:
星期日,2006年2月26日下午11点49由DmitryR异常对〜/路径?QS
是,我需要修复bug ......
Sunday, February 26, 2006 11:49 PM by DmitryR Exception on ~/path?qs
is a bug that I'll need to fix...
最简单的解决方法是保存/恢复的查询字符串
ResolveAp prelativeLinkToUrl
围绕呼叫
VirtualPathUtility.ToAbsolute
。
The easiest fix is to save/restore query string in
ResolveAppRelativeLinkToUrl
around the call to
VirtualPathUtility.ToAbsolute
.
一个解决办法是使用完全合格UTLS,而不是〜/...".
A workaround is to use fully qualified UTLs instead of "~/...".
谢谢
梅德
其中, ResolveAp prelativeLinkToUrl
指的是记者的code的方法名。
where ResolveAppRelativeLinkToUrl
refers to the reporter's code's method name.
另一个解决办法是更换?
的调用之前一个安全令牌 VirtualPathUtility.ToAbsolute
和反向更换算账:
Another workaround would be to replace ?
with a safe token before the call to VirtualPathUtility.ToAbsolute
, and reverse the replacement afterwards:
public static string SafeToAbsolute(string path)
{
var madeSafe = path.Replace("?", "UNLIKELY_TOKEN");
var absolute = VirtualPathUtility.ToAbsolute(madeSafe);
var restored = absolute.Replace("UNLIKELY_TOKEN", "?");
return restored;
}
选择一个合适不可能令牌应用程序。
choosing a suitably unlikely token for your application.