【问题标题】:Routes don't work when default define in ASP.net MVC4在 ASP.net MVC4 中默认定义时路由不起作用
【发布时间】:2014-02-20 01:10:35
【问题描述】:

我有一个 MVC4 应用程序,我在 RouteConfig 中定义的路由可以正常工作,如下所示:

routes.MapRoute(
    "LocalizedDefault", "{lang}/{homePage}",
    new { controller = "Home", action = "Index", pageCode = "home" },
    new {lang = @"(en|es)", homePage = @"(home|inicio)"}
);

routes.MapRoute(
    "Flowers",
    "{lang}/{page}",
    new {controller = "Plants", action = "Flowers", pageCode = "flowers"},
    new {lang = @"(en|es)", page= @"(flowers|flores)"}
);

/* ... more routes ... */

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

您可以看到每条路由都有一个参数,我需要更改我的语言(我的业务逻辑),问题是当我放置没有任何参数(如 http://www.mydomain.com)的 url 时,它会加载我的默认页面,但我可以' t改变语言,因为我没有我的页面参数,然后我改变我的路线:

routes.MapRoute(
    "Flowers",
    "{lang}/{page}",
    new {controller = "Plants", action = "Flowers", pageCode = "flowers"},
    new {lang = @"(en|es)", page= @"(flowers|flores)"}
);

/* ... more routes ... */

routes.MapRoute(
    "Default",
    "{lang}/{page}",
    new { controller = "Home", action = "Index", pageCode = "home" },
    new {lang = @"(en|es)", page = @"(home|inicio)"}
);

现在我的网站在调用http://www.mydomain.com 时可以更改其语言,但其他路线不再起作用(例如:http://www.mydomain.com/en/flowers

【问题讨论】:

    标签: c# asp.net-mvc-4 routes


    【解决方案1】:

    尝试使用默认路由并将参数添加到您的网址,如下所示...

    http://mydomain.com/?lang=es
    

    然后在您的家庭控制器上执行索引操作...

    public ActionResult Index(String? lang){
        //do some stuff when lang != null
        return View();
    }
    

    【讨论】:

    • 我无法添加那个参数
    • 通过调用完整路径 mydomain.com/home/index?lang=es ?
    • 不,我很清楚,它适用于 mydomain.com/es/inicio 和 mydomain.com/en/home .... 但我还需要 mydomain.com 才能工作
    • 您可以在家庭控制器的索引操作中重定向到默认语言。 return RedirectToRoute(routeName);
    猜你喜欢
    • 2017-11-27
    • 1970-01-01
    • 1970-01-01
    • 2010-11-19
    • 2013-03-13
    • 1970-01-01
    相关资源
    最近更新 更多