我想定义一个带约束的路由,以便它只匹配已知的控制器名称。 这是为了允许我为同一表单的其他URL定义回退路由。
特别:
/User应该带我到用户控制器的索引操作(存在)
/History应该带我到History控制器的Index动作(存在)
/es由于不存在“es”控制器,因此应使用回退路由并将我带到具有语言参数值“es”的Home控制器的Index操作。
我需要这个,因为我需要提供一个带有语言代码的特殊URL,以便以给定的语言启动应用程序。 因此,现在需要区分路由中的有效控制器名称和语言名称。
如何实现RegisterRoutes来实现这一目标? 非常感谢!
编辑:我意识到我可以为每个控制器定义一个特定的路由,这是可以的(我没有一个zillion控制器)。 但我想知道我是否可以依靠通用约束来实现这一目标,这样我就不必定义单独的路由。
I want to define a route with a constraint so that it only matches known controller names. This is to allow me to define a fallback route for other URLs of the same form.
Specifically:
/UserShould take me to the Index action of the User controller (which exists)
/HistoryShould take me to the Index action of the History controller (which exists)
/esAs no "es" controller exists, should use the fallback route and take me to the Index action of the Home controller with a language parameter value of "es".
I need this because I have a requirement to provide a special URL with a language code to launch the app in a given language. So there is now a need to distinguish between valid controller names and language names in the routing.
How can I implement RegisterRoutes to achieve this? Many thanks!
Edit: I realize that I can define a specific route for each of my controllers, which is OK (I don't have a zillion controllers). But I'm wondering if I can rely on a generic constraint to achieve this so that I don't have to define individual routes.
最满意答案
定义路由时,使用“constraints”参数来处理此问题。
例如:
RouteTable.Routes.Add(new Route { Url = "{controller}/{action}", Constraints = new { controller = "User|History" }, Defaults = new { action = "Index" } }; RouteTable.Routes.Add(new Route { Url = "{languageCode}", Defaults = new { controller = "Home", action = "Index" } };添加的第一条路线将首先进行评估。 如果“控制器”的令牌与约束不匹配,则将评估添加的下一个路由并使用索引操作和参数languageCode中的语言令牌解析到Home控制器。 您可能还想为languageCode标记添加约束,以确保只匹配有效的语言。 然后你可以添加第三条路线作为全能路线。
您也可以使用路由处理程序来处理我在blogpost Localization和MVC中描述的languageCode。
When defining your routes, use the "constraints" parameter to handle this.
For instance:
RouteTable.Routes.Add(new Route { Url = "{controller}/{action}", Constraints = new { controller = "User|History" }, Defaults = new { action = "Index" } }; RouteTable.Routes.Add(new Route { Url = "{languageCode}", Defaults = new { controller = "Home", action = "Index" } };The first route added will be evaluated first. If the token for "controller" is not matched against the constraints, the next route added will be evaluated and resolve to the Home controller with the Index action and the language token in the parameter languageCode. You might want to add a constraint to the languageCode token as well, to make sure only valid languages are matched. Then you could possibly add a third route as a catch-all route.
You could also use a routehandler to deal with the languageCode as I have described in my blogpost Localization and MVC.
更多推荐
发布评论