views:

127

answers:

2

I'm trying to create an ASP.NET MVC2 route with a regular expression constraint to filter language names (like en-us, pt-br) but unfortunately it doesn't work. Have a look:

routes.MapRoute(
    "Culture", // Route name
    "{culture}", // URL with parameters
    new { controller = "Home", action = "Culture" }, // Parameter defaults
    new { culture = @"^[a-z]{2}-[a-z]{2}$" }
);

Does anyone have any idea?

Edit: The url i'm testing is http://localhost/en-us

+1  A: 

case sensitive perhaps?

"en-US"

So you need:

new { culture = @"^[a-z]{2}-[A-Z]{2}$" }

But use this one to make it case insensitive:

new { culture = @"^[a-zA-Z]{2}-[a-zA-Z]{2}$" }
Thomas Stock
I'm using http://localhost/en-us on the url, so it's lowercase just like the regular expression suggests. I'll add it to the question.
Rodrigo Waltenberg
A: 

I don't know why it doesn't work in your case but here's what works:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        "Culture",
        "{culture}",
        new { controller = "Home", action = "Culture" },
        new { culture = @"^[a-z]{2}-[a-z]{2}$" }
    );

    routes.MapRoute(
        "Default",
        "{controller}/{action}/{id}",
        new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}

Controller:

public class HomeController : Controller
{
    public ActionResult Culture(string culture)
    {
        return View();
    }
}

URL: http://example.com/en-us invokes successfully the Culture action on HomeController and passes en-us in the culture parameter.

Darin Dimitrov
Man! I forgot to set the Culture action before testing! Thanks for the light you gave me!
Rodrigo Waltenberg