MVC中重载的路由

时间:2014-08-01 04:21:14

标签: c# asp.net-mvc asp.net-mvc-routing

我希望生成以下网址

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
);

但是,这不符合预期。点击链接将我带到第一个注册的操作。

请说明此实施有什么问题。

1 个答案:

答案 0 :(得分:1)

您需要路线约束:

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
);