MapPageRoute - 不能在中间发送空字符串?

MapPageRoute - can't send empty strings in the middle?

在我正在维护的项目中 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.

当有值的变量之间有一个空字符串的变量时,似乎会抛出异常。 (这有意义吗?)我该怎么办?

这里的问题是重定向与路由不匹配,因为您错误地声明了可选值。使它们可选的唯一方法是具有这样的配置:

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 个参数中的任何一个不在重定向中时,这将始终有效。 但是,有一个问题 - 当您省略一个参数时,右侧的所有参数也将为空。这就是 built-in 路由的工作方式。如果参数右边没有值,则参数只能是可选的。

如果您希望所有 3 个参数都是可选的并且不必担心参数的传递顺序或组合,您有 2 个选项:

  1. 使用查询字符串参数
  2. 使用约定建立一系列路由,如

在处理具有大量可选参数的搜索表单时,查询字符串参数是简单得多的选项,因为它们可以按任何顺序和任意组合提供,而无需执行任何额外操作。他们很适合这个场景。