开发者

Can't figure out why this MVC2 route doesn't work

开发者 https://www.devze.com 2023-01-16 00:46 出处:网络
I\'m trying to create an ASP.NET MVC2 route w开发者_高级运维ith a regular expression constraint to filter language names (like en-us, pt-br) but unfortunately it doesn\'t work. Have a look:

I'm trying to create an ASP.NET MVC2 route w开发者_高级运维ith 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


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}$" }


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消