在我正在维护的项目中的Global.asax.cs中有一个看起来像这样的方法
private static void MapRouteWithName(string name, string url, string physicalPath, bool? checkPhysicalUrlAccess = null, RouteValueDictionary defaults = null)
{
Route route;
if ((checkPhysicalUrlAccess != null) && (defaults != null))
{
route = System.Web.Routing.RouteTable.Routes.MapPageRoute(name, url, physicalPath, checkPhysicalUrlAccess.Value, defaults);
}
else
{
route = System.Web.Routing.RouteTable.Routes.MapPageRoute(name, url, physicalPath);
}
route.DataTokens = new RouteValueDictionary();
route.DataTokens.Add("RouteName", name);
}
然后在Global.asax.cs中使用它来设置这样的路线:
MapRouteWithName("Change User", "User/Change/{id}/{organizationid}/{username}/{logonaccount}/{phone}", "~/User/Change.aspx", true,
new RouteValueDictionary { { "id", "0" }, { "organizationid", "0" }, { "username", "" }, { "logonaccount", "" }, { "phone", "" } });
然后在页面后面的代码中可以找到这样的内容:
Response.RedirectToRoute("Change User", new
{
id = userID,
organizationid = selectedOrganizationID,
username = userName,
logonaccount = logonAccount,
phone = phone
});
现在这在大多数情况下运行良好,但在这个特定的例子中,我不知道变量userName,logonAccount和phone是否实际包含某些内容或为空。例如,当userName为空(“”)并且logonAccount具有值(“abcde”)时,抛出异常:
System.InvalidOperationException: No matching route found for RedirectToRoute.
当变量之间存在具有值的变量时,似乎抛出了异常。 (这有意义吗?)我能做些什么呢?
答案 0 :(得分:1)
此处的问题是重定向与路由不匹配,因为您正确地声明了可选值。使它们成为可选项的唯一方法是使用如下配置:
routes.MapPageRoute(
routeName: "ChangeUser1",
routeUrl: "User/Change/{id}/{organizationid}/{username}/{logonaccount}/{phone}",
physicalFile: "~/User/Change.aspx",
checkPhysicalUrlAccess: true,
defaults: new RouteValueDictionary(new {
phone = UrlParameter.Optional,
})
);
routes.MapPageRoute(
routeName: "ChangeUser2",
routeUrl: "User/Change/{id}/{organizationid}/{username}",
physicalFile: "~/User/Change.aspx",
checkPhysicalUrlAccess: true,
defaults: new RouteValueDictionary(new
{
username = UrlParameter.Optional
})
);
当最后3个参数中的任何一个都不在重定向时,这将始终有效。 但是,有一个问题 - 当你省略一个参数时,右边的所有参数也都是空的。这就是内置路由的工作方式。如果参数右侧没有值,则该参数只能是可选的。
如果您想让所有3个参数都可选,而不必担心参数传递的顺序或组合,您有两个选择:
查询字符串参数是处理具有大量可选参数的搜索表单时更简单的选项,因为它们可以按任何顺序和任意组合提供,而无需执行任何额外操作。它们非常适合这种情况。