MVC中的路由过载

本文关键字:路由 MVC | 更新日期: 2023-09-27 18:15:51

我想生成以下url

http://example.com/routes/A

http://example.com/routes/alpha-to-beta

,对于这个实现,我添加了两个路由到Global.asax文件

routes.MapRoute(
  "routes", // Route name
  "routes/{routeName}", // URL with parameters
  new { controller = "busroute", action = "SingleRoute" } // Parameter defaults
);
routes.MapRoute(
  "alpharoutes", // Route name
  "routes/{alphRoute}", // URL with parameters
  new { controller = "busroute", action = "AlphabetRoute"  } // Parameter defaults
);

然而,这并不像预期的那样工作。点击链接只会把我带到第一个注册的操作。

请指出这个实现有什么问题

MVC中的路由过载

你需要一个路由约束:

public class SingleCharacterConstraint: IRouteConstraint
{
    public bool Match
        (
            HttpContextBase httpContext, 
            Route route, 
            string parameterName, 
            RouteValueDictionary values, 
            RouteDirection routeDirection
        )
    {
        if (!values.ContainsKey(parameterName))
          return false;
        var parameterValue = (string)values[parameterName];
        return !string.IsNullOrWhitespace(parameterValue)
          && parameterValue.Length == 1;
    }
}

然后重新排序你的映射,并添加约束:

routes.MapRoute(
  "alpharoutes", // Route name
  "routes/{alphRoute}", // URL with parameters
  new { controller = "busroute", action = "AlphabetRoute"  }, // Parameter defaults
  new { alphRoute = new SingleCharacterConstraint() }, // Constraint 
);
routes.MapRoute(
 "routes", // Route name
 "routes/{routeName}", // URL with parameters
 new { controller = "busroute", action = "SingleRoute" } // Parameter defaults
);