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?

3
  • your solution should work... any problem with it? Commented May 6, 2011 at 7:44
  • Yes it's only going for route which ever is registered ist... Commented May 6, 2011 at 7:55
  • try this: add Default on top of Localization Commented May 6, 2011 at 7:58

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

a question though can i add a constrait for ajax calls only?
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.