ASP.NET WebForms GetVirtualPath 始终返回 null
我刚刚开始接触 ASP.NET 路由,目前注册了两条路由:
routes.MapPageRoute(
"default",
"{Path}/{Name}.aspx{Query}",
"~/Default.aspx",
true,
new RouteValueDictionary { { "Name", "default" } },
new RouteValueDictionary { { "Name", @"[-_\w]+" } });
routes.MapPageRoute(
"home",
"{Name}.aspx{Query}",
"~/Default.aspx",
true,
new RouteValueDictionary { { "Name", "default" } },
new RouteValueDictionary { { "Name", @"[-_\w]+" } });
但是,当我尝试使用这些路由构建 url 时,我总是遇到异常。我尝试了这个:
private string GetVirtualPath(RouteValueDictionary values)
{
return RouteTable.Routes.GetVirtualPath(
null, values).VirtualPath;
}
还有这个:
private string GetVirtualPath(RouteValueDictionary values)
{
var wrapper = new HttpContextWrapper(HttpContext.Current);
return RouteTable.Routes.GetVirtualPath(
new RequestContext(wrapper,
RouteTable.Routes.GetRouteData(wrapper)),
values).VirtualPath;
}
无论哪种方式,当我调用时,我都会在 RouteTable.Routes.GetVirtualPath
上得到一个空引用异常:
GetVirtualPath(new RouteValueDictionary { { "Name", entity.Name } });
或者甚至:
GetVirtualPath(new RouteValueDictionary { { "Name", entity.Name }, { "Query", string.Empty } });
我在这里做错了什么?
I am just getting introduced to ASP.NET routing and have two routes registered at the moment:
routes.MapPageRoute(
"default",
"{Path}/{Name}.aspx{Query}",
"~/Default.aspx",
true,
new RouteValueDictionary { { "Name", "default" } },
new RouteValueDictionary { { "Name", @"[-_\w]+" } });
routes.MapPageRoute(
"home",
"{Name}.aspx{Query}",
"~/Default.aspx",
true,
new RouteValueDictionary { { "Name", "default" } },
new RouteValueDictionary { { "Name", @"[-_\w]+" } });
However, when I try to build urls using these routes, I always get an exception. I tried this:
private string GetVirtualPath(RouteValueDictionary values)
{
return RouteTable.Routes.GetVirtualPath(
null, values).VirtualPath;
}
and also this:
private string GetVirtualPath(RouteValueDictionary values)
{
var wrapper = new HttpContextWrapper(HttpContext.Current);
return RouteTable.Routes.GetVirtualPath(
new RequestContext(wrapper,
RouteTable.Routes.GetRouteData(wrapper)),
values).VirtualPath;
}
Either way, I get a null reference exception on RouteTable.Routes.GetVirtualPath
when I call:
GetVirtualPath(new RouteValueDictionary { { "Name", entity.Name } });
Or even:
GetVirtualPath(new RouteValueDictionary { { "Name", entity.Name }, { "Query", string.Empty } });
What could I be doing wrong here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想我会回答我自己的问题。问题出在我的路线限制上。一旦我删除了
new RouteValueDictionary { { "Name", @"[-_\w]+" } }
行,一切就开始工作了。I guess I'll answer my own question. The problem was with my route restrictions. Once I removed the lines with
new RouteValueDictionary { { "Name", @"[-_\w]+" } }
everything started working.