1

i am trying to create routes in asp.net mvc

    routes.MapRoute(
        "Localization", // Route name
        "{Culture}/{controller}/{action}/{id}", // URL with parameters
        new { Culture = "en-US", controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
    );
    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}", // URL with parameters
        new { controller = "Home", action = "Index"} // Parameter defaults
    );

concept is simple... controller should be able to called through en-us/Controller/Action or controller/action... is it possible?

Usman Masood
  • 1,937
  • 2
  • 17
  • 33

1 Answers1

2

Route constraints

You will have to use a route constraint on the first route that will define how culture string should be formed. Try this route definition instead:

routes.MapRoute(
    "Localization",
    "{Culture}/{controller}/{action}/{id}",
    new { Culture = "en-US", controller = "Home", action = "Index", id = UrlParameter.Optional },
    new { Culture = @"\w{2}(?:-\w{2})?" }
);
routes.MapRoute(
    "Default",
    "{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

Route constraint regular expression is not completely correct, because as much as I can recall there are cultures with three-letter codes. Regular expression that I've defined allows for general cultures as well like:

/en/Controller

or

/en-US/Controller
/en-UK/Controller

Adjust to your liking.

Robert Koritnik
  • 103,639
  • 52
  • 277
  • 404
  • a question though can i add a constrait for ajax calls only? – Usman Masood May 06 '11 at 09:01
  • 1
    @Usman: Basically you can yes. But you will have to write your own custom route constraint class that must implement `IRouteConstraint` interface. And since you get `HttpContext` in it, you could obtain information whether request is Ajax or not. – Robert Koritnik May 06 '11 at 10:26