3

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:

/User

Should take me to the Index action of the User controller (which exists)

/History

Should take me to the Index action of the History controller (which exists)

/es

As 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.

4

1 回答 1

3

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.

于 2012-09-20T09:24:33.437 回答