我刚刚介绍了 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 } });
我在这里做错了什么?